我想知道在Swift /“新”可可中是否有一些新的和令人惊叹的可能性来获得两个NSDates之间的天数?
例如,在Ruby中,我会这样做:
(end_date - start_date).to_i
发布于 2015-01-27 13:03:01
你还得考虑时差。例如,如果比较日期2015-01-01 10:00
和2015-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)
发布于 2015-08-23 17:33:38
以下是我对Swift 2的回答:
func daysBetweenDates(startDate: NSDate, endDate: NSDate) -> Int
{
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
return components.day
}
发布于 2016-08-17 03:40:24
我看到了几个Swift3答案,所以我将添加我自己的答案:
public static func daysBetween(start: Date, end: Date) -> Int {
Calendar.current.dateComponents([.day], from: start, to: end).day!
}
命名感觉更快,只有一行,并且使用了最新的dateComponents()
方法。
https://stackoverflow.com/questions/24723431
复制相似问题