如何在以下示例

时间:2016-06-11 01:15:52

标签: swift nsdate nsdatecomponents

我正在计算两个日期之间的日差,但我发现以下代码实际上给了我24小时的差异,而不是日期的差异。我有以下代码:

func daysBetweenDate(startDate: NSDate, endDate: NSDate) -> Int
{
    let calendar = NSCalendar.currentCalendar()

    let components = calendar.components([.Day], fromDate:startDate, toDate: endDate, options: [])

    return components.day
}

因此,对于以下示例,我得到了这个结果:

lastLaunch:2016-06-10 01:39:07 +0000

toady:2016-06-11 00:41:41 +0000

dayDiff:0

我原本预计天差为1,因为上次发布是在10日,今天是11日。如何更改代码以便为我提供日期的实际差异?

1 个答案:

答案 0 :(得分:2)

您可以使用日历方法日期BySettingHour来获取startDate和endDate的正午时间,以使您的日历计算不受时间敏感:

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
}