The accepted answer will not return the correct day number between two dates. You should also consider the time difference. For example, if you compare the dates 2015-01-01 10:00 and 2015-01-02 09:00 , the days between these dates will return as 0 (zero), since the difference between these dates is less than 24 hours (this is 23 hours) .
If your goal is to get the exact number of days between two dates, you can work around this problem as follows:
// Assuming that firstDate and secondDate are defined // ... let calendar = NSCalendar.currentCalendar() // Replace the hour (time) of both dates with 00:00 let date1 = calendar.startOfDayForDate(firstDate) let date2 = calendar.startOfDayForDate(secondDate) let flags = NSCalendarUnit.Day let components = calendar.components(flags, fromDate: date1, toDate: date2, options: []) components.day // This will return the number of day(s) between dates
Swift 3 and Swift 4 Version
let calendar = Calendar.current // Replace the hour (time) of both dates with 00:00 let date1 = calendar.startOfDay(for: firstDate) let date2 = calendar.startOfDay(for: secondDate) let components = calendar.dateComponents([.day], from: date1, to: date2)
Emin Buğra Saral Jan 27 '15 at 5:03 2015-01-27 05:03
source share