我如何计算以下示例中的日差 [英] How can I figure out the day difference in the following example
问题描述
我正在计算两个日期之间的天差,但我发现以下代码实际上给了我 24 小时的差异,而不是日期的差异.我有以下代码:
I am calculating the day difference between two dates, but I figured out the the following code is actually giving me the difference for 24 hours rather than the difference in date. I have the following code:
func daysBetweenDate(startDate: NSDate, endDate: NSDate) -> Int
{
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate:startDate, toDate: endDate, options: [])
return components.day
}
所以,对于下面的例子,我得到了这个结果:
So, for the following example I get this result:
lastLaunch:2016-06-10 01:39:07 +0000
lastLaunch:2016-06-10 01:39:07 +0000
今天:2016-06-11 00:41:41 +0000
toady: 2016-06-11 00:41:41 +0000
dayDiff:0
我原以为天差是 1,因为上次发布是在 10 日,而今天是 11 日.如何更改代码以提供几天的实际日期差异?
I would have expected the day difference to be one, since last launch was on the 10th and today is the 11th. How can I change the code to give me the actual difference in date for days?
推荐答案
你可以使用 Calendar 方法 date BySettingHour 来获取你的 startDate 和 endDate 的中午时间,让你的日历计算对时间不敏感:
You can use Calendar method date BySettingHour to get the noon time for your startDate and endDate, to make your calendar calculations not time sensitive:
Xcode 8.2.1 • Swift 3.0.2
extension Date {
var noon: Date? {
return Calendar.autoupdatingCurrent.date(bySettingHour: 12, minute: 0, second: 0, of: self)
}
func daysBetween(_ date: Date) -> Int? {
guard let noon = noon, let date = date.noon else { return nil }
return Calendar.autoupdatingCurrent.dateComponents([.day], from: noon, to: date).day
}
}
let startDateString = "2016-06-10 01:39:07 +0000"
let todayString = "2016-06-11 00:41:41 +0000"
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "ex_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss xxxx"
if let startDate = formatter.date(from: startDateString),
let endDate = formatter.date(from: todayString),
let days = startDate.daysBetween(endDate) {
print(startDate) // "2016-06-10 01:39:07 +0000\n"
print(endDate) // "2016-06-11 00:41:41 +0000\n"
print(days ?? "nil") // 1
}
<小时>
Swift 2.x
extension NSDate {
var noon: NSDate {
return NSCalendar.currentCalendar().dateBySettingHour(12, minute: 0, second: 0, ofDate: self, options: [])!
}
}
func daysBetweenDate(startDate: NSDate, endDate: NSDate) -> Int {
return NSCalendar.currentCalendar().components([.Day],
fromDate: startDate.noon,
toDate: endDate.noon,
options: []).day
}
这篇关于我如何计算以下示例中的日差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!