iOS: Compare two dates
According to Apple documentation of NSDate compare:
Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.
- (NSComparisonResult)compare:(NSDate *)anotherDate
Parameters
anotherDate
The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X.
Return Value
If:
The receiver and anotherDate are exactly equal to each other,
NSOrderedSame
The receiver is later in time than anotherDate,
NSOrderedDescending
The receiver is earlier in time than anotherDate,
NSOrderedAscending
In other words:
if ([date1 compare:date2] == NSOrderedSame) ...
Note that it might be easier in your particular case to read and write this :
if ([date2 isEqualToDate:date2]) ...
After searching, I've got to conclusion that the best way of doing it is like this:
- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate{ NSDate* enddate = checkEndDate; NSDate* currentdate = [NSDate date]; NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate]; double secondsInMinute = 60; NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute; if (secondsBetweenDates == 0) return YES; else if (secondsBetweenDates < 0) return YES; else return NO;}
You can change it to difference between hours also.
If you want to compare date with format of dd/MM/yyyy only, you need to add below lines between NSDate* currentdate = [NSDate date];
&& NSTimeInterval distance
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];[dateFormatter setDateFormat:@"dd/MM/yyyy"];[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];currentdate = [dateFormatter dateFromString:stringDate];
I take it you are asking what the return value is in the comparison function.
If the dates are equal then returning NSOrderedSame
If ascending ( 2nd arg > 1st arg ) return NSOrderedAscending
If descending ( 2nd arg < 1st arg ) return NSOrderedDescending