两个NSDates之间的快速日子 [英] Swift days between two NSDates
问题描述
我想知道是否有一些新的和可怕的可能性来获得Swift /新Cocoa中两个NSDates之间的天数?
I'm wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the "new" Cocoa?
例如。就像在Ruby中我会这样做:
E.g. like in Ruby I would do:
(end_date - start_date).to_i
推荐答案
接受的答案不会在两个日期之间返回正确的日期编号。你也必须考虑时差。例如,如果您比较日期 2015-01-01 10:00
和 2015-01-02 09:00
,这些日期之间的天数将返回0(零),因为这些日期之间的差异小于24小时(23小时)。
The accepted answer won't return the correct day number between two dates. You have to consider the time difference as well. For example if you compare the dates 2015-01-01 10:00
and 2015-01-02 09:00
, days between those dates will return as 0 (zero) since the difference between those dates is less than 24 hours (it's 23 hours).
如果您的目的是为了获得两个日期之间的确切日期数,您可以解决此问题,如下所示:
If your purpose is to get the exact day number between two dates, you can work around this issue like this:
// 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 3 Version
let calendar = NSCalendar.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)
这篇关于两个NSDates之间的快速日子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!