Does anybody know what is going on here?
I'm looking for all first weekdays in a year.
let calendar = Calendar(identifier: .gregorian)
let year = calendar.dateInterval(of: .year, for: .now)!
// ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
print(calendar.standaloneWeekdaySymbols)
// 1
print(calendar.firstWeekday)
let firstWeekdayDateComponents = DateComponents(
hour: 0,
minute: 0,
second: 0,
nanosecond: 0,
weekday: calendar.firstWeekday
)
calendar.enumerateDates(
startingAfter: year.start,
matching: firstWeekdayDateComponents,
matchingPolicy: .strict
) { date, _, stop in
guard let date = date, date < year.end else {
stop = true
return
}
print(DateFormatter.localizedString(from: date, dateStyle: .short, timeStyle: .none))
}
It prints
02/01/2022
09/01/2022
16/01/2022
...
04/12/2022
11/12/2022
18/12/2022
where I'm missing the last expected value - 25/12/2022.
If I try to reconstruct that expected date, with components with the same precision, the calendar is able to do so.
let missingDateDateComponents = DateComponents(
year: 2022,
month: 12,
day: 25,
hour: 0,
minute: 0,
second: 0,
nanosecond: 0,
weekday: calendar.firstWeekday
)
let missingDate = calendar.date(from: missingDateDateComponents)!
// 25/12/2022
print(DateFormatter.localizedString(from: missingDate, dateStyle: .short, timeStyle: .none))
// year: 2022 month: 12 day: 25 hour: 0 minute: 0 second: 0 nanosecond: 0 weekday: 1 isLeapMonth: false
print(calendar.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond, .weekday], from: missingDate))
// true
print(missingDate < year.end)
Am I missing something?