Ega Setya Putra
Ega Setya Putra

Reputation: 1695

How to convert String to NSDate?

I have string that I received whenever there is new remote notifications.I'm using parse for my Backend. And String that I retrieved come from "createdAt" column.

I've tried below code:

    var ca = "2015-07-03T03:16:17.220Z"
    var dateFormater : NSDateFormatter = NSDateFormatter()
    dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
    let date = dateFormater.dateFromString(ca)

    println(date)

But the println is giving me nil, I think there is something wrong with my date format. How can I fix this?

Upvotes: 0

Views: 213

Answers (1)

Rob
Rob

Reputation: 437432

You are missing the milliseconds. Thus:

dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

Note, when converting from the date string to a NSDate, you shouldn't quote the Z. If you quote the Z, it will match the literal Z character, but won't correctly reflect that this date string is actually Zulu/GMT/UTC.


If you want to create formatter that also goes the other way, converting NSDate objects to strings, in that case you should quote the Z, but in that case you must remember to explicitly set the timezone:

dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormater.timeZone = NSTimeZone(forSecondsFromGMT: 0)

By the way, don't forget to set the locale as per Apple Technical Q&A 1480.

dateFormater.locale = NSLocale(localeIdentifier: "en_US_POSIX")

Upvotes: 5

Related Questions