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.
Asked
Active
Viewed 89 times
-1
-
What language? What datatypes? The strategy used can vary wildly. – Hobadee Nov 09 '18 at 17:22
-
@Hobadee The question is tagged Swift. The link in this question refers to a question in Swift. – rmaddy Nov 09 '18 at 17:23
-
Have a look at this answer https://stackoverflow.com/a/40193009/1187415 to the referenced question. – Martin R Nov 09 '18 at 17:27
1 Answers
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
-
-
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
-
-
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