user1007522 user1007522 - 2 months ago 9
iOS Question

dateFormat always returns nil

I'm getting a dateFormat from the server like this:

2016-09-04T17:44:44+02:00


So I wrote a dateformatter:

private static let jsonDateFormatter: NSDateFormatter = {
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+SSS"
return fmt
}()


there is still a problem because when I do
jsonDateFormatter.dateFromString
it returns nil so the dateFormat must be wrong.

I don't see the problem.

Answer

As per the Documentation given on Apple Docs here

The correct formatter for this type of Dates will be

yyyy-MM-dd'T'HH:mm:ssZZZZZ

As it is used in the give example

let RFC3339DateFormatter = NSDateFormatter()
RFC3339DateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
//RFC3339DateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)

/* 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time) */
let string = "1996-12-19T16:39:57-08:00"
let date = RFC3339DateFormatter.dateFromString(string)
Comments