Reputation: 127
When I run this I get a result when I use OrderedDescending or OrderedAscending but not OrderedSame, even though the dates for newyear are the same.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "mm/dd/yyyy"
let christmas = dateFormatter.dateFromString("12/25/2015")
let newyear = dateFormatter.dateFromString("11/29/2015")
let update = dateFormatter.dateFromString("02/01/2016")
let date2 = NSDate()
if date2.compare(newyear!) == NSComparisonResult.OrderedSame {
let alertController = UIAlertController(title: "", message:
"Happy New Year. ", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
if date2.compare(christmas!) == NSComparisonResult.OrderedDescending {
let alertController = UIAlertController(title: "", message:
"Merry Christmas.", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}De
Upvotes: 3
Views: 1066
Reputation: 12768
Well your first issue is your date format. You need "MM/dd/yyyy". Also, NSDate()
returns the current date (including time), so it is not exactly the same as a date from format "MM/dd/yyyy" which does not include the given time, even if the day of the year is the same. So you should use NSCalendar
's date comparison function using the unit granularity .Day, rather than NSDate's compare function.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let newyear = dateFormatter.dateFromString("11/29/2015")
let date2 = NSDate() // Currently 11/29/2015
let order = NSCalendar.currentCalendar().compareDate(newyear!, toDate: date2,
toUnitGranularity: .Day)
if order == NSComparisonResult.OrderedSame {
print("same")
}
Upvotes: 3