Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to know if two NSDate instances are both from the same day.

Is there an easier/better way to do it than getting the NSDateComponents and comparing day/month/year?

like image 548
Prody Avatar asked Oct 13 '09 16:10

Prody


3 Answers

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];
}
like image 186
progrmr Avatar answered Oct 20 '22 00:10

progrmr


If you are working with iOS 8 you can use -isDate:inSameDayAsDate:.

From NSCalendar.h:

/*
    This API compares the Days of the given dates, reporting them equal if they are in the same Day.
*/
- (BOOL)isDate:(NSDate *)date1 inSameDayAsDate:(NSDate *)date2 NS_AVAILABLE(10_9, 8_0);

Note that for some reason this didn't make it to the official documentation on Apple's developer site. But it is definitely part of the public API.

like image 43
Joe Masilotti Avatar answered Oct 20 '22 01:10

Joe Masilotti


(Note: Look at Joe's answer for a good way to do this on iOS 8+)

I just use a date formatter:

NSDateFormatter *dateComparisonFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateComparisonFormatter setDateFormat:@"yyyy-MM-dd"];

if( [[dateComparisonFormatter stringFromDate:firstDate] isEqualToString:[dateComparisonFormatter stringFromDate:secondDate]] ) {
    …
}

HTH.

like image 27
Ben Lachman Avatar answered Oct 20 '22 01:10

Ben Lachman