Search code examples
swiftdateswift-playground

Completely illogical Date() values, in Swift


When I try to add a time interval to a given date at the end of some of the months, I get illogical results.

In the following example, when I add 5 hours to an 8:00PM time, in the given date, the resulted date will be the following at 1:00AM, which is expected. But if I add 6 hours instead of 5, the result will be the date after the following at 2:00AM, which completely doesn't make sense.

import SwiftUI

let calendar = Calendar(identifier: .islamic)
let formatter = DateFormatter()
formatter.calendar = calendar
formatter.dateFormat = "dd/MM/yyyy HH:mma"

let components = DateComponents(calendar: calendar, year: 1445, month: 7, day: 29, hour: 20, minute: 0, second: 0)
let givenDate = calendar.date(from: components)!
let after_5_hours = givenDate.advanced(by: 60 * 60 * 5)
let after_6_hours = givenDate.advanced(by: 60 * 60 * 6)

formatter.string(from: givenDate)      // = "29/07/1445 20:00PM"
formatter.string(from: after_5_hours)  // = "30/07/1445 01:00AM"
formatter.string(from: after_6_hours)  // = "01/08/1445 02:00AM"

Update: The behavior occurs while using islamic calendar. I couldn't reproduce it in gregorian calendar


Solution

  • Using Calendar(identifier: .islamicCivil) fixes the problem.