ghostpotato ghostpotato - 1 year ago 73
Swift Question

Two NSDates created next to each other do not compare equal

This code, comparing two

s created one after the other, does not enter the
case as I would expect.

import UIKit

let chosenDate = NSDate()

let currentDate = NSDate()

let formatter = NSDateFormatter()
formatter.dateFormat = "EEEE"

let day = formatter.stringFromDate(chosenDate)

var result = String()

switch {

case .OrderedSame:
result = "Today is a \(day)"
case .OrderedAscending:
result = "That was a \(day)"
case .OrderedDescending:
result = "That will be a \(day)"


Whenever I run this (in a playground or [I pulled this into a playground from my project file to test stuff] in the Simulator) it gives me "That was a (insert day here) instead of "Today is a (insert day here). Why is this?

Answer Source

The values of chosenDate and currentDate are not the same. If you print the values of the dates, you will see that they are different, likely by a few milliseconds.

If you want to check if the days are the same, you need to try the NSCalendar method compareDate:toDate:toUnitGranularity:

You can use NSCalendarUnitDay to compare if the dates are on the same day.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download