-1

I have two dates. startDate and endDate which are one day apart. From the print function I get:

startDate: 2023-01-01 05:07:33 +0000 endDate: 2023-01-01 17:08:04 +0000

Of course this is UTC so the day is inaccurate but if I get the Calendar.Component .day for each date then I get 1 and 2 respectively which is what I expect.

I am trying to calculate the number of days between these two dates using: Calendar.current.dateComponents([.day], from: startDate, to: endDate).day

However this is returning 0. What am I don't wrong here? From what I understand since this function is using the Calendar then it should ignore the UTC format and return 1.

Kex
  • 8,023
  • 9
  • 56
  • 129
  • It has nothing to do with timezone. The difference is 12 hours, 31 seconds. That's less than 1 day. See https://stackoverflow.com/a/28163560/20287183 for a solution. – HangarRash Jan 01 '23 at 17:29

1 Answers1

0

The function you use calculates the difference in full days between the two dates and not if they are on different days

This can be easily verified with the below example

let endDate = Date.now
let firstDate = Calendar.current.date(byAdding: .hour, value: -23, to: endDate)!
print(Calendar.current.dateComponents([.day], from: firstDate, to: endDate).day!)
let secondDate = Calendar.current.date(byAdding: .hour, value: -24, to: endDate)!
print(Calendar.current.dateComponents([.day], from: secondDate, to: endDate).day!)

which prints

0
1

The same goes for an hour where -59 minutes returns 0 and -60 returns 1

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52