Date를 UTC 와 KST로 출력하기 - swift
27 Nov 2018 | swiftUTC 와 KST로 출력하기 - swift
중요한 사실
NSDate 또는 Date 객체는 타임존 정보를 포함하지 않고 모두 UTC기준입니다. 따라서 해당 지역의 시각으로 표현하기 위해서는 DateFormatter를 사용해야 합니다.
Apple 개발자 사이트에서 명확한 내용을 아직 찾지 못해 SO에 있는 내용을 잠시나마 발췌합니다.
ref: https://stackoverflow.com/questions/1268509/ios-convert-utc-nsdate-to-local-timezone
I disagree. NSDate does NOT have a timezone. To specify the timezone for the NSDate, you use an NSCalendar object or an NSDateFormatter object. If you create an NSDate from a string that has no timezone specified, then the NSDate will assume that the string is in GMT time. – Rickster Dec 3 ‘13 at
다음은 Date객체를 현재 timeZone에 맞게 출력하기 위해 String으로 변환하는 extension 함수입니다.

코드:
extension Date {
func toString( dateFormat format: String ) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.locale = Locale.current
return dateFormatter.string(from: self)
}
func toStringKST( dateFormat format: String ) -> String {
return self.toString(dateFormat: format)
}
func toStringUTC( dateFormat format: String ) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
return dateFormatter.string(from: self)
}
}
추가로 lldb를 통해 아래 정보도 확인이 가능합니다.
(lldb) po dateFormatter.locale
▿ Optional<Locale>
▿ some : en_KR (current)
- identifier : "en_KR"
- kind : "current"
Eddie Kwon - Development log for ML, iOS
Comments