Monday, April 20, 2020 [Tweets] [Favorites]

NSDateFormatter.com

NSDateFormatter.com is an interactive reference for date format strings and has some good tips (via Kyle Howells):

  • Use dateStyle and timeStyle over dateFormat whenever you can. Explain the date fallacies to your designer if you need to.
  • If you can’t find a fitting dateStyle/timeStyle to format your UI dates, then at least use dateFormatter.setLocalizedDateFormatFromTemplate(…) to account for the user’s locale.
  • When parsing ISO8601 internet dates, always use ISO8601DateFormatter
  • If you can’t because your API format doesn’t fit ISO8601 and you still absolutely need to use a custom dateFormat, then be sure to also set your dateFormatter.locale to the special value Locale(identifier: "en_US_POSIX").

See also: goshdarnblocksyntax.com, goshdarnswiftui.com.

Previously:

Update (2020-04-22): Tyler Hall:

Why wasn’t it crashing for us in our testing?

[…]

Apple’s documentation for that method says…

Returns a date representation of a given string interpreted using the receiver’s current settings.

[…]

The customer dictated their bug report to us via email using Siri. They speak English, live outside Boston, but their phone’s region was set to Uzbekistan instead of United States (or anything else more common).

4 Comments

`ISO8601DateFormatter` is unfortunately not suitable if you need to support dates with fractional seconds in Swift JSON decoding.
`JSONDecoder.DateDecodingStrategy.iso8601` does not support fractional seconds at the moment. And if you want to provide your own formatter through `JSONDecoder.DateDecodingStrategy.formatted(DateFormatter)` you can't use `ISO8601DateFormatter` as it is a subclass of `Formatter` but not a `DateFormatter`.

@Yurly ISO8601DateFormatter has an option called “ withFractionalSeconds” that should do what you need.

@Yuriy I guess that’s because ISO8601DateFormatter doesn’t support the same options that DateFormatter does? It seems like there should be another layer in there like AbstractDateFormatter that is guaranteed to return a date so that could be used with cases like JSONDecoder.

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment