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