Renato Probst
Renato Probst

Reputation: 6054

Compare two NSDate by .Day in swift is giving wrong results

Im trying to compare two NSDate by .Day doing this (both on gmt timezone):

 var order = NSCalendar.currentCalendar().compareDate(event.startDate!, toDate: cell.date!,
                    toUnitGranularity: .Day)
                    if (order == .OrderedSame) {
                            print(String(event.startDate!) + " == " + String(cell.date!))
                        cell.events.append(event)
                        break
                    }

When using 2016-03-08 21:43:53 +0000 and 2016-03-09 00:00:00 +0000 it says they are orderedSame, but they arent, the days are different. This function outputs:

 2016-03-08 21:43:53 +0000 == 2016-03-09 00:00:00 +0000

Can someone help me please?

Upvotes: 1

Views: 494

Answers (1)

rmaddy
rmaddy

Reputation: 318794

Those two logged dates are being logged in the UTC timezone. But if your current timezone is west of that, then both dates are on March 8, 2016 in your timezone and the comparison is done in your timezone. Or, if you live east of that by at least 2.5 hours, then both dates are March 9, 2016.

Example. If you live in the eastern USA (GMT-4 currently but GMT-5 on March 8), then those two dates are actually 2016-03-08 16:43:53 -0500 and 2016-03-08 19:00:00 -0500.

Example. If you live in eastern Europe or Asia (say GMT+5), then those two dates would be 2016-03-09 02:43:53 +0500 and 2016-03-09 05:00:00 +0500.

As you can see, those are on the same day so the comparison is correct.

Upvotes: 7

Related Questions