简体   繁体   中英

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

Having a problem with NSDateFormatter.

So I have a date string formatted "yyyy-MM-dd" , 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

"2015-09-31"

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.

Your code is correct and produces the expected result eg 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.

var str = "2015-09-29"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let dateAsNSDate = dateFormatter.dateFromString(str)
print(dateAsNSDate)
// -> "Optional(2015-09-29 07:00:00 +0000)\n"

So that would appear to work. Looks like you just got too many days in your month, so it wasn't a valid date! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM