iOS에서 날짜를 표현할 때는 Date
또는 NSDate
객체를 사용한다.
개발자 문서에서는 Date
를 다음과 같이 설명한다.
A
Date
value encapsulate a single point in time, independent of any particular calendrical system or time zone.
즉, Date
객체는 시간대(timezone)나 calendar system에 영향을 받지 않는 기준시(GMT) 날짜를 나타낸다. Date
인스턴스를 console에 출력해 보면 시간이 다르게 출력된다.
let today = Date()
print(today)
// 현재 날짜 : 2021-06-04 11:16
// 출력된 날짜 : 2021-06-04 02:16:22 +0000
GMT(Greenwich Mean Time)는 런던 그리니치 천문대의 경도를 기준으로 하는 기준시이다. 1970년 1월 1일을 기점으로 사용하는 UTC(협정 세계시)와 표현만 다른 같은 개념이다.
시간대(timezone)는 그리니치 천문대를 기준 경도(0)로 하여 세계 각국의 경도값에 따라 시간차가 발생하는 범위이다. 국가 별 경도를 사용하여 기준시(GMT)로부터 얼마 만큼의 시간차가 발생하는지 계산한다.
국가별 local timezone은 'GMT+시차'로 표현한다. 우리나라는 GMT+9 시간대에 속해 있다.
Date
객체는 기준시에 따른 날짜를 나타내므로, 우리 나라 시간대에 맞는 날짜/시간을 사용하려면 GMT+9 시간대의 시차를 적용해야 한다.
Date
를 시간대에 맞게 사용하기 위해서는 시간대 별 시차를 적용해야 한다. Timezone
인스턴스의 secondsFromGMT(for:)
method를 사용하여 현재 시간대의 시차를 구하고, Date
인스턴스에 시차를 더하면 현재 날짜/시간을 정확하게 얻을 수 있다.
let today = Date()
let timezone = Timezone.autoupdatingCurrent
let secondsFromGMT = timezone.secondsFromGMT(for: today)
let localizedDate = today.addingTimeInterval(TimeInterval(secondsFromGMT))
print(localizedDate)
DateFormatter
를 사용하면 지정한 시간대로 변경된 Date
를 다룰 수 있다.
func localizedRepresentation(_ date: Date, format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.dateFormat = format
return dateFormatter.string(from: date)
}
let localizedDate = localizedRepresentation(today, format: "yyyy-MM-dd HH:mm")
print(localizedDate)