I was trying to find a robust way of getting the end of the current year in Swift and tried this:
let yearComponent = Calendar.current.dateComponents([.year], from: Date.now)
return Calendar.current.nextDate(
after: Date.now,
matching: yearComponent,
matchingPolicy: .nextTime,
repeatedTimePolicy: .last,
direction: .forward
)
To my surprise, this always returns nil
. I'm trying to understand why. While, depending on the precision required, there might be simpler solutions, I'm interested in why this solution does not work and if there is a better/working solution that returns the last possible moment of the current year.
We don't know what is the exact implementation of this nextDate method (unless it's code is available somewhere) but theoretically there is infinite amount of dates after Date.now with current year so I guess that perhaps it might be implemented in such way that it always increases given component at least once (and starts searching from first possible date after this increase) and only after that it checks if proper date was found and this is the reason why it does not find any date in your case.
Anyway you could do something like in the code below to get the last second of the current year so maybe this will be enough for your needs:
let yearComponent = Calendar.current.dateComponents([.year], from: Date.now)
let yearStart = Calendar.current.date(from: yearComponent)
let nextYearStart = yearStart.flatMap({ Calendar.current.date(byAdding: .year, value: 1, to: $0) })
let yearEnd = nextYearStart?.addingTimeInterval(-1)
print("yearEnd = \(yearEnd)")
I'm not sure what exactly you are trying to achieve but "last possible moment" is hard to define as again theoretically it can have infinite precision so probably you should just use nextYearStart from above example and compare other dates with that.