I’m trying to get previous dates that matches specific months in the year. It mainly works but for an unknown reason, it does not work as expected for the 9nth month in the Gregorian calendar (which is September). When the after date is Date.now (currently in December), I expect the previous September month to be in 2023. But the first date returned is in 1995.
var calendar: Calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone.autoupdatingCurrent
let matchingDateComponents: DateComponents = DateComponents(month: 09)
let date: Date? = calendar.nextDate(
after: Date.now,
matching: matchingDateComponents,
matchingPolicy: .nextTime,
direction: .backward
)
I tested with other time zones and the results are different... For some time zones, the result is correct, for others, it's not. Why? Do you have any idea @eskimo @davedelong?
- Optional(1970-08-31 23:00:00 +0000) for Europe/London
- Optional(1995-08-31 23:00:00 +0000) for Europe/Paris
- Optional(2002-08-31 22:00:00 +0000) for Europe/Vilnius
- Optional(2023-09-01 07:00:00 +0000) for America/Los_Angeles
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(date, zone)
}
I filed a feedback for that: FB13462533