I’m not sure what your goal is, but setting a fixed-format date string without pinning the locale to en_US_POSIX
is almost always a mistake. The three standard approaches for DateFormatter
are:
-
If the date is meant to be seen (or input) by users, you should be using one of the predefined formats:
let d = Date() let s1 = DateFormatter.localizedString(from: d, dateStyle: .short, timeStyle: .none) print(s1) // -> 04/03/2019
-
If you need more control over user-visible date strings, use a template:
let df = DateFormatter() df.setLocalizedDateFormatFromTemplate("MM/yyyy") let s2 = df.string(from: d) print(s2) // -> 03/2019
-
If you’re dealing with date strings that aren’t user visible (from a network protocol header, for example), use either
ISO8601DateFormatter
or theen_US_POSIX
locale.
Trying to mix’n’match these approaches generally doesn’t end well. QA1480 NSDateFormatter and Internet Dates has a specific example of how things can go wrong (but there are many others).
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple