NSDateFormatter to parse ISO8601 with and without milliseconds

cocoa, datetime, objective-c

Solution

For "2013-07-23T13:45:02Z" Use: "yyyy-MM-dd'T'HH:mm:ssZ"

For "2013-07-23T13:45:02.677Z" Use: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

Check the date format string to see which to use or try one and if it fails try the other.

See: ICU Formatting Dates and Times

Problem

Is it possible to have a `NSDateFormatter` parse both an ISO8601 date with and without milliseconds. I have the following 2 date formats being returned by an API and sometimes they have milliseconds included and sometimes not. For example I might have `2013-07-23T13:45:02Z` and `2013-07-23T13:45:02.677Z`. For the former setting the `dateFormat` property to `@"yyyyMMdd'T'HHmmss'Z'"` works fine. Is there a format I can use to parse the later, optionally parsing the milliseconds if they exist?

Original source

Related problems