[자바/Java] Date, SimpleDateFormat, TimeZone, Locale에 관하여

프로그래밍/자바2020. 3. 22. 11:16

간단하게 제가 이해한.. Date, SimpleDateFormat, TimeZone, Locale에 대해 정리해보려고 합니다.

 

Locale이 시간대와 관련된 것이라고 생각했는데.. 아닌 것 같습니다.

시간대라기 보다는.. 각 지역에 맞는 표현방법?과 관련되어 있습니다.

예를 들어.. Locale이 미국이라면, 일요일을 표현할 때 "Sun"으로 표현됩니다.

Locale이 한국이라면 일요일은 "일요일"로 표현됩니다.

 

 

SimpleDateFormat을 이용하여

1. 텍스트로 표현되어 있는 시간을 parse하여 Date로 저장할 때,

2. Date를 텍스트로 표현되는 시간으로 format(출력?)할 때

 

이 두 경우 모두.. TimeZone과 관련되어 있습니다.

 

따로 TimeZone을 명시하지 않으면 안드로이드에서는 기본적으로 설정된 단말의 시간대 정보가 사용됩니다.

TimeZone.getDefault() 가 사용됩니다.

 

만약 단말의 TimeZone과 다른 시간대로 표현된 문자열을 파싱하여.. 현재의 시간대로 표현하려면 아래와 같이 사용하면 됩니다.

String writeDate = "2020-03-22 01:43:11";

Date date = null;
String formattedDate = null;

SimpleDateFormat dfYearMonthDayHourMinuteSecond = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
dfYearMonthDayHourMinuteSecond.setTimeZone(TimeZone.getTimeZone("GMT")); 

try {
    date = dfYearMonthDayHourMinuteSecond.parse(writeDate);
} catch (ParseException e) {
    e.printStackTrace();
}

SimpleDateFormat dfYearMonthDayHourMinuteSecondWithDayOfWeek = new SimpleDateFormat("yyyy-MM-dd(EEE) HH:mm:ss", Locale.getDefault());

formattedDate = dfYearMonthDayHourMinuteSecondWithDayOfWeek.format(date); 

formattedDate는 2020-03-22(Sun) 10:43:11의 값을 가지게 됩니다.

 

작성자

Posted by 드리머즈

관련 글

댓글 영역