Skip to content

ISO8601DateFormatter

Ken Harris edited this page Nov 26, 2018 · 1 revision

New in 10.12, but you probably don't want to use it, anyway. It's not what you think it is -- if you think it sounds like a class that lets you pass an ISO-8601 string to it and get a Date back. The catch is that it only supports a couple ISO-8601 sub-formats, and you have to declare exactly which sub-format you're using when you configure it (with an OptionSet)!

So for example:

  • Want to parse "2015-01-01T12:34:45Z"? Need to use .formatOptions = [.withFullDate, .withFullTime]
  • Want to parse "2015-01-01"? Need to use .formatOptions = [.withFullDate] (and can't use .withFullTime)
  • Want to parse "2015W0011"? Need to use .formatOptions = [.withYear, .withWeekOfYear, .withDay]
  • Want to parse "2015-W1-1"? Sorry, not supported by Foundation's ISO8601DateFormatter.

(There's also NSDataDetector, which can parse some ISO-8601 strings, but note that it's a lot slower than any date-only parser, and still doesn't support the less common sub-formats. Apple's documentation specifically cautions not to use it for ISO-8601.)

Peter Hosey's ISO8601DateFormatter is a pretty good replacement that actually works in all of these cases without needing to be specially configured each time. Don't be scared by the fact that it's ancient (pre-ARC!) Objective-C code. It works. There's some newer native Swift ones that look pretty but fall down in not-uncommon use cases.

Clone this wiki locally