Comparing two NSDates and ignoring the time component
I'm surprised that no other answers have this option for getting the "beginning of day" date for the objects:
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay startDate:&date1 interval:NULL forDate:date1];
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay startDate:&date2 interval:NULL forDate:date2];
Which sets date1
and date2
to the beginning of their respective days. If they are equal, they are on the same day.
Or this option:
NSUInteger day1 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit: forDate:date1];
NSUInteger day2 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitEra forDate:date2];
Which sets day1
and day2
to somewhat arbitrary values that can be compared. If they are equal, they are on the same day.
You set the time in the date to 00:00:00 before doing the comparison:
unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* dateOnly = [calendar dateFromComponents:components];
// ... necessary cleanup
Then you can compare the date values. See the overview in reference documentation.