I have an application that works perfectly with the Gregorian calendar. All the API data and date calculations in the app are based on the Gregorian calendar. However, I'm facing crashes when users have their devices set to a different calendar type, such as the Buddhist calendar.
For instance, the following function crashes when a non-Gregorian calendar is active:
func days(from date: Date) -> Int {
let beginningOfDay = date.beginningOfDay ?? date
return Int(timeIntervalSince1970 - beginningOfDay.timeIntervalSince1970) / Int(TimeInterval.day)
}
Issue: I want to ignore the user's calendar settings and enforce the Gregorian calendar throughout the application. I'm aware of calendar converters, but I don’t want to convert dates individually. Instead, I need a way to ensure that the Gregorian calendar is consistently applied across the app.
Question: Is there a way to force the Gregorian calendar globally across the app so that all date-related functions and operations adhere to it? If so, how can I implement this?
This looks like you've added a lot of extensions on Date
that don't belong there. Date
is a point in time. In order to talk about "days" you should be calling Calendar
and DateComponents
methods. This function isn't quite correct anyway. It can be off by a day depending on DST changes. You can't assume that a day is 24 hours long; some are 25 hours, and some are 23 hours.
The code you wanted was:
let calendar = Calendar(identifier: .gregorian)
calendar.dateComponents([.day], from: d1, to: d2).day!
Likely somewhere in your extensions you have Calendar.current
. That means "the current user calendar." There's no way to tell the system "even when I explicitly ask for the current user calendar, please give me something else." Look for the code that uses Calendar.current
and replace it with Calendar(identifier: .gregorian)
if that's what you mean.