kangarooChris kangarooChris - 2 years ago 74
Swift Question

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

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

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


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?

Answer Source

You can use NSCalendar method dateBySettingHour to get the noon time for your startDate and endDate, to make your calendar calculations not time sensitive:

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


let startDateString = "2016-06-10 01:39:07 +0000"
let todayString = "2016-06-11 00:41:41 +0000"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss xxxx"
if let startDate = formatter.dateFromString(startDateString),
 endDate = formatter.dateFromString(todayString) {
    print(startDate)  // "2016-06-10 01:39:07 +0000\n"
    print(endDate)    // "2016-06-11 00:41:41 +0000\n"
    print(daysBetweenDate(startDate, endDate: endDate)) // 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download