yyMMdd 날짜 포맷의 이상한 결과

Jongwon Woo
3 min readSep 23, 2020

--

iOS DateFormatter의 ‘yyMMdd’ 포맷을 사용해서 ‘000101’을 변환하면…

12099–12–31 15:00:00 +0000

이 나온다. 이상하다.

let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .gregorian)
dateFormatter.timeZone = .current
dateFormatter.locale = .current
dateFormatter.dateFormat = “yyMMdd”
print(dateFormatter.date(from: “000101”)!) // 12099–12–31

더 이상한 점은 ‘000102’를 변환하면…

2000–01–01 15:00:00 +0000

이 나온다는 것이다.

timeZone과 locale이 영향을 주는 것 같은데…

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: “en_US_POSIX”)
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = “yyMMdd”
print(dateFormatter.date(from: “000101”)!) // 2000–01–01 00:00:00 +0000

이제 제대로 나오는 것 같다. 그런데 1900년이 아니라 2000년이다.

이런 동작의 힌트는 DateFormatter.twoDigitStartDate 프로퍼티에서 찾을 수 있다. 문서를 보면 기본값은 1949년 12월 31일이다.

dateFormatter.twoDigitStartDate = formatter.date(from: “19000101”)!
print(dateFormatter.date(from: “000101”)!) // 1900–01–01 00:00:00 +0000

이제 1900년으로 나온다.

그런데 timeZone을 바꾸면…

dateFormatter.timeZone = TimeZone(secondsFromGMT: 3600)
print(dateFormatter.date(from: “000101”)!) // 12099–12–31 23:00:00 +0000

다시 이상해진다.

--

--