Search code examples
iosobjective-cnsdate

Format date string with .000Z into NSDate


I would like to format a date string into a NSDate object, which doesn't sound like a big thing.

The point is, that the date string contains a dot in the timezone value instead of a plus or something else. A date looks like this:

2017-06-04T16:00:00.000Z

I tried format strings like

yyyy-MM-dd'T'HH:mm:ss.ZZZZ
yyyy-MM-dd'T'HH:mm:ss.ZZZ
yyyy-MM-dd'T'HH:mm:ss.Z

Of course I've also checked it on nsdateformatter.com, which works but in xCode the NSDate is always nil.


Solution

  • This work for me

    var str = "2017-06-04T16:00:00.000Z"
    let formato = DateFormatter()
    formato.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    formato.timeZone = NSTimeZone(name: "UTC")! as TimeZone
    formato.formatterBehavior = .default
    var data = formato.date(from: str)