Search code examples
iosswiftnscalendar

Why my comparison of two dates doesn't work as it should?


I have two dates (date and NSDate()) that I want to compare based on their day. When I do the following:

println(NSDate())
println(date)
println(NSCalendar.currentCalendar().compareDate(date, toDate: NSDate(), toUnitGranularity: .DayCalendarUnit) == .OrderedSame)

I get this in the output:

2015-04-27 04:16:49 +0000
2015-04-26 23:57:35 +0000
true

It's clear (at least on the output) that the days are different but the compareDate method says there are the same.

Somebody can explain me why please?


Solution

  • When you output a date, don't use simple println, which gives you the date/time in London. Instead, do it like this:

    println(date.descriptionWithLocale(NSLocale.currentLocale()))
    

    That will give you a clearer idea of what date-time is involved, because it will correspond to where you are located.

    If you do that with your dates, you will find that they are in fact situated within the same day.