mankee mankee - 2 months ago 15
iOS Question

DateFormatter Changes Date by 500 Years

I am running the following code :

if let messagedate = curr_comment["timestamp"] as? String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.dateFromString(messagedate)

and here is the debugger output :

enter image description here

This started happening randomly today, I'm not sure why the date changes by 500 years through such a simple operation.

Rob Rob

It is because the device in question is not set for Gregorian calendar. It is using the Buddhist calendar. See Apple Technical Q&A 1480 which discusses the proper handling of date strings to gracefully handle international calendars.

If this yyyy-MM-dd HH:mm:ss format is for internal purposes (storing in database, communicating with web service, etc.), you should consider setting the locale of the formatter to en_US_POSIX. In Swift 3:

dateFormatter.locale = Locale(identifier: "en_US_POSIX")

in Swift 2:

dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")

Frankly, this also begs the question as to what timezone the string representation of the date is using. You generally would want to make sure that date/time strings are consistently stored in UTC/GMT. In Swift 3:

dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

Or, in Swift 2:

dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)

If you do that consistently throughout the app, you'll avoid weird timezone issues (e.g. if someone in NY posts something right now, I don't want it to tell me in CA that it happened three hours ago).