-1

can anyone explain how can I get difference between two dates in calendar days, not in whole 24-hour periods. There is a good solution here: Getting the difference between two NSDates in (months/days/hours/minutes/seconds) -- but it doesn't work for me as, for example, it gives the difference between 23:00 today and 1:30 tomorrow as 0 days despite of calendar dates differ already by 1.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Dmytro
  • 9
  • 2

1 Answers1

0

Use the normal way to calculate the difference in days with one change - convert both of your dates to midnight.

let d1 = ... // your first date
let d2 = ... // your second date
let cal = Calendar.current
let days = cal.dateComponents([.day], from: cal.startOfDay(for: d1), to: cal.startOfDay(for: d2)).day!

This will give an answer of 1 for "yesterday at 23:00" and "today at 1:30", for example.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thank you for such an elegant idea. – Dmytro Nov 10 '18 at 18:04
  • This would return 0 days if you try to calculate the difference between the first day of a daylight savings date (which used to start at 1am here in Brazil) and the day after which starts at 12am. You should use noon for days calculation. – Leo Dabus Sep 25 '19 at 21:55
  • try `let cal = Calendar.current let timeZone = TimeZone(identifier: "America/Sao_Paulo")! let date1 = DateComponents(calendar: cal, timeZone: timeZone, year: 2001, month: 10, day: 14).date! let date2 = DateComponents(calendar: cal, timeZone: timeZone, year: 2001, month: 10, day: 15).date! cal.dateComponents([.day], from: date1, to: date2).day!` – Leo Dabus Sep 25 '19 at 22:01
  • @LeoDabus Why not post your own answer? – rmaddy Sep 25 '19 at 22:02
  • I am just warning you that this doesn't work, I have already talked about the same issue with Martin R. You can keep your answer as it is you you would like to – Leo Dabus Sep 25 '19 at 22:03