How can I figure out the day difference in the following example

非 Y 不嫁゛ 提交于 2019-12-02 08:40:41

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!