Cocoa-Touch: How do I see if two NSDates are in the same day?

If you are targeting iOS 8 (and OS X 10.9) or later, then Joe’s answer is a better solution using a new method in NSCalendar just for this purpose:

-[NSCalendar isDate:inSameDayAsDate:]

For iOS 7 or earlier: NSDateComponents is my preference. How about something like this:

- (BOOL)isSameDayWithDate1:(NSDate*)date1 date2:(NSDate*)date2 {
    NSCalendar* calendar = [NSCalendar currentCalendar];

    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];

    return [comp1 day]   == [comp2 day] &&
           [comp1 month] == [comp2 month] &&
           [comp1 year]  == [comp2 year];
}

Leave a Comment