Provide general advice like using en_US_POSIX or setLocalizedDateFormatFromTemplate
See original GitHub issueAs discussed on Slack, here are the suggestions / rules I always give to anyone willing to use a custom date format:
If possible it’s better to always avoid providing the
dateFormat
yourself, because it’s so easy to get it wrong for other locales by doing it yourself, you’re gonna run into some fallacies. A good set of rules are the following:
- Use
dateStyle
andtimeStyle
whenever you can instead ofdateFormat
- If you need a specific format that can’t be achieved by dateStyle and timeStyle, then at least use
df.setLocalizedDateFormatFromTemplate(…)
, ordf.dateFormat = DateFormatter.dateFormat(fromTemplate:…options:…locale:…)
to make sure it auto-adapts to the user’s locale; never use a directString
format as thedateFormat
field to format dates for UI.- If you need to parse ISO Dates / “internet dates” used not for UI but for JSON or API, etc, preferably use
ISO8601DateFormatter
- In last resort, if you need to parse a date for JSON or API that doesn’t fall into ISO8601 format, but that also isn’t intended for UI and should not depend on the user’s locale/region/language because it’s a format for the API not for presenting in UI, then that’s the only case when you can use a fixed string in
df.dateFormat
likedf.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
BUT when you do that, then ALWAYS also setdf.locale = Locale(identifier: "en_US_POSIX")
. This is a special locale for your DateFormatter that guarantees that the formatting/parsing won’t depend on the phone’s locale and is designed exactly for parsing those “internet dates with fixed format”
@davedelong suggested that we post that advice on nsdateformatter.com as we think that could be very valuable to a lot of people.
The think is, I’m not sure how to do this. Do we want a new page / tab next to “Examples / Reference / About” on the website, with this as static content? Do we want something else, maybe some ⚠️ icon next to the Locale
dropdown linking to said advice? I’m open to suggestions.
(Also, I just copy/pasted my Slack message verbatim here, but we might need a more appropriate wording to present that as static content on the website ofc)
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (6 by maintainers)
Yep. Feel free to ping me on Slack if you run into any issues.
Best Practices?