0

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.

Jacob King
  • 6,025
  • 4
  • 27
  • 45
  • This should work for "2015-09-22" (and it does in my test). For "2015-09-31", `nil` is returned because September has only 30 days. – Martin R Sep 22 '15 at 14:58

2 Answers2

2

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Wow! I can't believe I was that stupid! For this example payload.objectForKey("messageExpiry") was being set manually by me elsewhere so I was to blame for the incorrect value. Easily done I suppose... Thank You! – Jacob King Sep 22 '15 at 15:11
1
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! :)

Mark
  • 12,359
  • 5
  • 21
  • 37