Search code examples
swift2ios9nsdate

Date compare returning wrong value? (swift)


I'm trying to compare two dates by Day in swift. Following this solution wrote the following code:

let workoutdate: NSDate = participantdata[self.lastindexchecked].workout!.start!
let todaysdate = NSDate()
let order = NSCalendar.currentCalendar().compareDate(todaysdate, toDate: workoutdate, toUnitGranularity: .Day)

switch order {
case .OrderedDescending:
    print("DESCENDING")
case .OrderedAscending:
    print("ASCENDING")
case .OrderedSame:
    print("SAME")
}

However, this code does not seem to always be returning the desired result.

todaysdate is equal to:

2016-08-20 20:51:26 +0000

When workoutdate is equal to :

2016-08-20 00:14:53 +0000

The result is "DESCENDING"

However, when the workout date is set to a different one, eg,

2016-08-20 04:00:00 +0000

The result is indeed "SAME" as predicted.

Anyone have any idea what is going on?


Solution

  • NSDate is a fundamental construct in Foundation so bugs like this would have been detected and fixed long ago. Before you think it's an Apple's bug, think about your own bug first. And most of the headache dealing with dates involving the timezone.

    I'm in the EDT (-0400) timezone so:

    todaysdate  = 2016-08-20 20:51:26 +0000 = 2016-08-20 16:51:26 -0400
    workoutdate = 2016-08-20 00:14:53 +0000 = 2016-08-19 20:14:53 -0400
    

    You can see how when expressed in my timezone, they fall on different days and DESCENDING is exactly what's expected here.

    You can solve this in a few ways by setting your calendar to always use GTM:

    let calendar = NSCalendar.currentCalendar()
    calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
    let order = calendar.compareDate(todaysdate, toDate: workoutdate, toUnitGranularity: .Day)