Post

Replies

Boosts

Views

Activity

date(byAdding:value:to:options:) Method Behaves Strangely
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?
1
0
77
Apr ’25