I stumbled across this answer and while your answer is correct it still misses one point. The DateFormatter produces wrong string results.
Especially when using the Locale en_US_POSIX
Just run the following code in playground:
let dfWithLocale: DateFormatter = {
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "YYYY-MM-dd'T'HH:mm:ss"
df.timeZone = TimeZone(secondsFromGMT: 0)
return df
}()
let dfWithoutLocale: DateFormatter = {
let df = DateFormatter()
df.dateFormat = "YYYY-MM-dd'T'HH:mm:ss"
df.timeZone = TimeZone(secondsFromGMT: 0)
return df
}()
var date = Date().addingTimeInterval(-60*60*24*365*3)
while date < Date() {
let stringWithLocale = dfWithLocale.string(from: date)
let stringWithoutLocale = dfWithoutLocale.string(from: date)
print("Date: \(date) as StringWithLocale \(stringWithLocale) as StringWithoutLocale \(stringWithoutLocale)")
date = date.addingTimeInterval(60*60*24)
}
This produces wrong output exactly around December 26 to December 31!
Here is the relevant output. In the middle the date as string using the locale, on the right the string using no locale and on the left the date with string interpolation.
Date: 2021-12-24 08:18:57 +0000 as StringWithLocale 2021-12-24T08:18:57 as StringWithoutLocale 2021-12-24T08:18:57
Date: 2021-12-25 08:18:57 +0000 as StringWithLocale 2021-12-25T08:18:57 as StringWithoutLocale 2021-12-25T08:18:57
Date: 2021-12-26 08:18:57 +0000 as StringWithLocale 2022-12-26T08:18:57 as StringWithoutLocale 2021-12-26T08:18:57
Date: 2021-12-27 08:18:57 +0000 as StringWithLocale 2022-12-27T08:18:57 as StringWithoutLocale 2021-12-27T08:18:57
Date: 2021-12-28 08:18:57 +0000 as StringWithLocale 2022-12-28T08:18:57 as StringWithoutLocale 2021-12-28T08:18:57
Date: 2021-12-29 08:18:57 +0000 as StringWithLocale 2022-12-29T08:18:57 as StringWithoutLocale 2021-12-29T08:18:57
Date: 2021-12-30 08:18:57 +0000 as StringWithLocale 2022-12-30T08:18:57 as StringWithoutLocale 2021-12-30T08:18:57
Date: 2021-12-31 08:18:57 +0000 as StringWithLocale 2022-12-31T08:18:57 as StringWithoutLocale 2021-12-31T08:18:57
Date: 2022-01-01 08:18:57 +0000 as StringWithLocale 2022-01-01T08:18:57 as StringWithoutLocale 2021-01-01T08:18:57
I am not sure when this started to go wrong. I am running this with macOS 13.2.1. Running the same in the playground for iOS gives the same result.