Home > OS >  Searching for date backwards with `nextDate(after:matching...` just strangely long in time?
Searching for date backwards with `nextDate(after:matching...` just strangely long in time?

Time:10-31

I use nextDate(after:matching:matchingPolicy:repeatedTimePolicy:direction:) to search for a date backwards.

I want to search for the 23rd of the month before, but I get a jump to from 2022 to 1995.

Is this a bug or am I just missing something calendar-wise that makes this result actually correct?

var calendar: Calendar = .autoupdatingCurrent
calendar.timeZone = TimeZone(identifier: "Europe/Stockholm")!

let date = Date(timeIntervalSince1970: 1666310400.0) // "Oct 21, 2022 at 2:00 AM"
print(date) // "2022-10-21 00:00:00  0000\n"
calendar.nextDate(after: date, // "Sep 23, 1995 at 12:00 AM" ??
                  matching: DateComponents(day: 23),
                  matchingPolicy: .previousTimePreservingSmallerComponents,
                  direction: .backward)

CodePudding user response:

Here is a simple alternative to accomplish the same thing

var previous = calendar.date(bySetting: .day, value: 23, of: date)!
while previous > date {
    previous = calendar.date(byAdding: .month, value: -1, to: previous)!
}
  • Related