CraigH CraigH - 1 month ago 12
Swift Question

NSDateFormatter always returning nil.

I am trying to convert a date time string from Django Rest Framework such as this:
"2014-10-28T18:14:32.457" into a Swift string. I am running the following code in a playground and always get the error:

fatal error: unexpectedly found nil while unwrapping an Optional value

import Foundation

var mydate = "2014-10-28T18:14:32.457"
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
formatter.timeStyle = .ShortStyle
formatter.dateStyle = .ShortStyle
var parsedDateTimeString = formatter.dateFromString(mydate)
formatter.stringFromDate(parsedDateTimeString!)


I think its because dateFromString is always returning nil. But I cant figure out why its returning nil. Im pretty sure i have the dateFormat correct. Where am i going wrong?

Answer

If you're setting dateFormat, then you shouldn't set timeStyle or dateStyle (they'll override the format you set). You also might want to think about using optional binding instead of forced unwrapping to make your code a little safer:

var mydate = "2014-10-28T18:14:32.457"
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
if let parsedDateTimeString = formatter.dateFromString(mydate) {
    formatter.stringFromDate(parsedDateTimeString)
} else {
    println("Could not parse date")
}

Running that in a Playground and looking at the stringFromDate line results in:

2014-10-28T18:14:32.457