안드로이드

[안드로이드] SimpleDateFormat

loasd 2022. 12. 20. 18:04
반응형

https://github.com/lnjky/fashion_people

 

GitHub - lnjky/fashion_people: 패션 추천 어플

패션 추천 어플. Contribute to lnjky/fashion_people development by creating an account on GitHub.

github.com

코드 전체를 보려면 위에 링크를 통해 확인할 수 있습니다.

 


 

어플을 만들 때 현재 시간을 데이터로써 입력을 해야 하거나 시간을 출력해서 화면에 보여야 할 때가 있다.

그럴때 현재 시간을 가져와야 하는데 그 방법에 대해 설명하고자 한다.

 

기본적인 형식은 이렇다.

    long now = System.currentTimeMillis();
    java.util.Date mDate = new Date(now);
    // 날짜, 시간의 형식 설정
    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
    String current_time = simpleDateFormat1.format(mDate);

SimpleDateFormat에 원하는 형식을 넣으면 형식에 맞춘 날짜를 가져온다.

이 값은 current_time을 통해 setText()를 해서 텍스트를 배치할 수 있고

Log.을 사용하거나 System.out을 통해 로그캣에서 값이 제대로 나오는지 확인할 수 있다.

나는 어플을 만들때 시간에 따라 바뀌는 날씨를 받아오기 위해 사용하였다.

 

        long now = System.currentTimeMillis();
        Date mDate = new Date(now);

        // 날짜, 시간의 형식 설정
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("HH");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM");

        // 현재 날짜를 받아오는 형식 설정 ex) 20221121
        String getDate = simpleDateFormat1.format(mDate);
        String getTime = simpleDateFormat2.format(mDate) + "00";
        String CurrentTime = simpleDateFormat2.format(mDate) + ":00";
        String getSeason = simpleDateFormat.format(mDate);

이렇게 여러개의 simpleDateFormat을 만들고 각각의 형식을 만든 다음 활용할 수도 있다.

아래의 String들은 각각 이런 값을 나타낸다.

String getDate = simpleDateFormat1.format(mDate);			//20221220
String getTime = simpleDateFormat2.format(mDate) + "00";		//0600
String CurrentTime = simpleDateFormat2.format(mDate) + ":00";		//06:00
String getSeason = simpleDateFormat.format(mDate);			//12   ( 월 )

이런식으로 활용해서도 사용할 수 있다.

그런데 잘 보면 m과 M이 대소문자로만 구분되어있어 헷갈릴 수 있는데 이는 다음의 표에서  확인할 수 있다

주로 사용하는 것은 y, M, d, h, H, m, s 이다.

대문자 소문자 차이로 다른 값이 나올 수 있어 잘 보고 작성해야 한다.

M은 Month의 월을 나타내고 m은 minute의 분을 나타내므로 잘 보고 작성하도록 하자

 

 

반응형