小编典典

两个NSDate之间的短暂日子

swift

我想知道是否有一些新的和令人敬畏的可能性来获取Swift /“新”可可中两个NSDate之间的天数?

例如像在Ruby中,我会这样做:

(end_date - start_date).to_i

阅读 247

收藏
2020-07-07

共1个答案

小编典典

您还必须考虑时差。例如,如果您比较日期2015-01-01 10:002015-01-02 09:00,则这些日期之间的天数将返回0(零),因为这些日期之间的时差小于24小时(即23小时)。

如果您的目的是获取两个日期之间的确切天数,则可以这样解决此问题:

// 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和Swift 4版本

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)
2020-07-07