两个 NSDates 之间的 Swift 天数 [英] Swift days between two NSDates
问题描述
我想知道是否有一些新的和很棒的可能性来获取 Swift 中两个 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 小时).
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 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)
这篇关于两个 NSDates 之间的 Swift 天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!