我想知道是否有一些新的和令人敬畏的可能性来获取Swift /“新”可可中两个NSDate之间的天数?
例如像在Ruby中,我会这样做:
(end_date - start_date).to_i
您还必须考虑时差。例如,如果您比较日期2015-01-01 10:00和2015-01-02 09:00,则这些日期之间的天数将返回0(零),因为这些日期之间的时差小于24小时(即23小时)。
2015-01-01 10:00
2015-01-02 09:00
如果您的目的是获取两个日期之间的确切天数,则可以这样解决此问题:
// 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
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)