Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two dates(dates only; not time) in cocoa?

Basically, I want to figure out if it's the next day. So, I'm storing the current date (e.g. Jan 2) constantly in a plist. But the next time the user opens the application, if the date has changed (e.g. Jan 3), I want to do something. Note that a simple ascending order check wouldn't work because I don't want to know if one date is later than another date, if the difference is only in hours. I need to be able to differentiate Jan 2 11:50 and Jan 3 2:34 but not Jan 3 2:34 and Jan 3 5:12.

like image 452
abiraja Avatar asked Jan 03 '10 11:01

abiraja


1 Answers

I use the following that I found SO:

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

    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    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 121
Niels Castle Avatar answered Oct 19 '22 14:10

Niels Castle