Let’s try calculating one day after "2023/11/04 12:00 New York time".
let timeZone = TimeZone(identifier: "America/New_York")! var calendar = Calendar(identifier: .gregorian) calendar.timeZone = timeZone var dateFormatter = DateFormatter() dateFormatter.timeZone = timeZone dateFormatter.locale = .init(identifier: "ja_JP") dateFormatter.dateStyle = .short dateFormatter.timeStyle = .short var dateComponents = DateComponents() dateComponents.year = 2023 dateComponents.month = 11 dateComponents.day = 4 dateComponents.hour = 12 // At New York 2023/11/04 12:00 let date1 = calendar.date(from: dateComponents)! print(dateFormatter.string(from: date1)) // Add 1 day let date2 = calendar.date(byAdding: .day, value: 1, to: date1)! print(dateFormatter.string(from: date2))```
The output is:
2023/11/04 12:00 2023/11/05 12:00
Now, let’s try the following—also to get the time one day later:
let date2 = calendar.date(byAdding: .minute, value: 24 * 60, to: date1)! print(dateFormatter.string(from: date2))
This outputs:
2023/11/04 12:00 2023/11/05 11:00
What's Causing This Difference?
It’s likely due to Daylight Saving Time (DST). But why do we get different results between the first and second examples?
Because in 2023, DST in the US ended on 5 Nov 2023. See here.
Because:
-
In the first example, you add a day. This ensures that the time stays the time.
-
In the second example, you add 1,440 minutes. This ensure that the difference between the two dates is exactly 1,440 minutes minutes.
The existence of days that aren’t exactly 1,440 minutes means that you have to choose one or the other invariant; you can’t have both.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"