Compare two NSDates for same date/time

Greg picture Greg · Apr 12, 2011 · Viewed 16.8k times · Source

Is date1 == date2 not a valid way to compare? If not, what is the correct alternative?

Here's my code:

- (NSDate*) dateWithNoTime {
    unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:flags fromDate:self];
    NSDate* dateOnly = [calendar dateFromComponents:components];
    return dateOnly;
}

- (BOOL) sameDayAsDate:(NSDate*)dateToCompare {
    NSDate *date1 = [self dateWithNoTime];
    NSDate *date2 = [dateToCompare dateWithNoTime];
    return date1 == date2;       // HERE IS WHERE THINGS SEEM TO FAIL

}

Answer

Kirk Kelsey picture Kirk Kelsey · Apr 12, 2011

You're comparing two pointer values. You need to use the NSDate comparison method like:

return ([date1 compare:date2] == NSOrderedSame);