Search code examples
iosswiftfoundationiso8601

swift 4.1 ISO8601DateFormatter doesn't parse dates passed by MRAID ad content


I don't have control over what date string is passed to me, and in the case of the MRAID 2.0 test ads (IAB) they use this odd date format:

2013-12-21T00:00-05:00

This does parse fine in some date formatters I've tested.. but not using ISO8601DateFormatter.

If I add the extra zeros:

2013-12-21T00:00:00-05:00, then it works but again, I can't control what I'm sent.

Is there any way to configure it to read this date format?


Solution

  • Just use a regular DateFormatter with the needed dateFormat of yyyy-MM-dd'T'HH:mmZZZZZ and be sure to set the formatter's locale to en_US_POSIX.

    If you get date strings in multiple possible formats then try one format, if that returns nil, try the next possible format. Repeat for all the possible formats you have to handle.