In Swift, why does Calendar nextDate/enumerateDates methods with backward direction does not provide a date before September 1995?

54 views Asked by At

I’m trying to get the previous date that matches the 9nth month in the Gregorian calendar (which is September) from Date.now (which is in December 2023 right now). The expected date is then in 2023. The first date returned is in 1995 for my time zone. Why?

I filed the feedback FB13462533

let matchingDateComponents: DateComponents = DateComponents(month: 09)
                        
let date: Date? = Calendar.autoupdatingCurrent.nextDate(
    after: Date.now,
    matching: matchingDateComponents,
    matchingPolicy: .nextTime,
    direction: .backward
)
            
print(date) // Optional(1995-08-31 23:00:00 +0000)

I just tested with other time zones and the results are different... For some time zones, the result is correct, for others, not.

  • Europe/London, Optional(1970-08-31 23:00:00 +0000)
  • Europe/Paris, Optional(1995-08-31 23:00:00 +0000)
  • Europe/Vilnius, Optional(2002-08-31 22:00:00 +0000)
  • America/Los_Angeles, Optional(2023-09-01 07:00:00 +0000)

I used the following code to print the result for all time zones.

for zone in TimeZone.knownTimeZoneIdentifiers {
    var calendar: Calendar = Calendar(identifier: .gregorian)
    calendar.timeZone = TimeZone(identifier: zone) ?? .autoupdatingCurrent
                
    let matchingDateComponents: DateComponents = DateComponents(month: 9)
                
    let date: Date? = calendar.nextDate(
        after: Date.now,
        matching: matchingDateComponents,
        matchingPolicy: .nextTime,
        direction: .backward
    )
                
    print(zone, date)
}
0

There are 0 answers