ellman121 ellman121 - 7 months ago 50
Swift Question

NSDateFormatter how_to

I am reading a JSON object and it includes a when field. The when field is formatted "m-d-yyyy h:m:s"

So for instance, a date string could be "5-25-2016 5:30:2"

Since I do not know the length of m, d, h, m, and s, how can I get an NSDate out of these strings?

EDIT: Using one of the tools from the comments, I've made some progress. The website properly identifies the date (adds 6 hours for time shift, but I can fix that). However, I'm still having issues on the device.

let dateFrmtr = NSDateFormatter()
dateFrmtr.dateFormat = "MM-dd-yyyy HH:MM:SS"
dateFrmtr.locale = NSLocale(localeIdentifier: "en_US_POSIX")

print(dateFrmtr.dateFromString(mov["when"]! as! String)!) <-- prints "2016-10-08 01:00:00 +0000"
print(mov["when"]!) <-- prints "6-7-2016 19:10:3"

This is not the correct behaviour.


By using pretty much exactly what you have shown!

let df = NSDateFormatter()
df.dateFormat = "M-d-yyyy H:m:s"
df.dateFromString("5-25-2016 5:30:2") // works
df.dateFromString("12-25-2016 15:30:22") // works as well

The docs state "Use one or two for zero padding" for all of M, s and H, the others work the same way. That means: use two letters for zero padding, e.g. MM for 05 - or only one letter for omitting leading zeros: M for 5. That works both for parsing and for outputting dates.

The changes I made for you contain of chaning the first M to upper case since that is the correct letter for months. Same for the hours.

Note that the parsing is powerful enough to work even when providing more letters:

df.dateFormat = "MM-dd-yyyy HH:mm:ss"
df.dateFromString("1-5-2016 1:3:2") // works too

The formatting is more important for transforming the date back to a string!