Jacob King Jacob King - 1 year ago 115
Swift Question

NSDateFormatter.dateFromString returns nil ("yyyy-MM-dd" to NSDate)

Having a problem with NSDateFormatter.

So I have a date string formatted

, for example 2015-09-22.
However when I pass this into NSDateFormatter.dateFromString, the method returns nil. My code is as follows:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let dateAsNSDate = dateFormatter.dateFromString(payload.objectForKey("messageExpiry") as! String)

From the debugger console at a breakpoint just above this code:

po payload.objectForKey("messageExpiry") as! String


I have explored other questions similar to this but am as of yet still unable to fix this problem.
Any and all help would be appreciated.

Answer Source

Your code is correct and produces the expected result e.g. for the input string "2015-09-22". For the input "2015-09-31" however, nil is returned because that is an invalid date: September has only 30 days.

You can set

dateFormatter.lenient = true

and then "2015-09-31" is accepted and treated as "2015-10-01". But you should check first why payload.objectForKey("messageExpiry") returns an invalid date.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download