I know how to use Date components and check how many days, hours, years etc. have passed between 2 dates.
However, what I want to know is whether the new date is the next day from a pervious day.
For example the last day could be March 12 2022 11:59PM And the new day could be March 13 2022 12:01 AM that would count as the next day.
Calculating the difference between the two dates would result in 2 min but that's not what I want. I want to check whether it's the next day.
How do I go about this?
CodePudding user response:
What you need is calendar method isInSameDay
as date. So first you get your second date and get its day after as shown here How to get date for tomorrow and yesterday (take care special case) new month or new year, then you just need to check if it is in same day as the first date Something like:
extension Date {
var dayBefore: Date {
Calendar.current.date(byAdding: .day, value: -1, to: noon)!
}
var dayAfter: Date {
Calendar.current.date(byAdding: .day, value: 1, to: noon)!
}
var noon: Date {
Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
func isInSameDay(as date: Date) -> Bool {
Calendar.current.isDate(self, inSameDayAs: date)
}
func isDayBefore(_ date: Date) -> Bool {
isInSameDay(as: date.dayBefore)
}
func isDayAfter(_ date: Date) -> Bool {
isInSameDay(as: date.dayAfter)
}
}
Usage:
let cal = Calendar(identifier: .iso8601)
let date1 = DateComponents(calendar: cal, year: 2022, month: 3, day: 12, hour: 23, minute: 59).date!
let date2 = DateComponents(calendar: cal, year: 2022, month: 3, day: 13, hour: 0, minute: 1).date!
date1.isDayBefore(date2) // true
date2.isDayAfter(date1) // true
date1.isDayAfter(date2) // false
date2.isDayBefore(date1) // false
CodePudding user response:
The correct solution for this kind of problem is to calculate the difference while ignoring time. The simplest method to do that is to start using DateComponents
instead of Date
.
Let's create some testing data first:
let parser = ISO8601DateFormatter()
parser.formatOptions = .withInternetDateTime
let date1 = parser.date(from: "2022-03-12T23:59:00Z")!
let date2 = parser.date(from: "2022-03-13T00:01:00Z")!
Let's show the problem:
var calendar = Calendar.current
// make sure to set time zone correctly to correspond with the test data above
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
let componentDiff = calendar.dateComponents([.day], from: date1, to: date2)
print(componentDiff.day!) // 0
Now let's see the solution:
// take only the day components, ignoring the time
let components1 = calendar.dateComponents([.year, .month, .day], from: date1)
let components2 = calendar.dateComponents([.year, .month, .day], from: date2)
// calculate the difference only between the day components
let componentDiff2 = calendar.dateComponents([.day], from: components1, to: components2)
print(componentDiff2.day!) // 1