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

前端 未结 1 712
庸人自扰
庸人自扰 2021-01-27 14:21

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 d

1条回答
  •  -上瘾入骨i
    2021-01-27 14:32

    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
    }
    

    0 讨论(0)
提交回复
热议问题