There are 4 methods for comparing NSDate
s in Objective-C:
- (BOOL)isEqualToDate:(NSDate *)anotherDate
- (NSDate *)earlierDate:(NSDate *)anotherDate
- (NSDate *)laterDate:(NSDate *)anotherDate
- (NSComparisonResult)compare:(NSDate *)anotherDate
Consider the following example using 2 dates, NSDate date1 = July 7, 2016
and NSDate date2 = July 2, 2016
:
NSDateComponents *comps1 = [[NSDateComponents alloc]init];
comps.year = 2016;
comps.month = 7;
comps.day = 7;
NSDateComponents *comps2 = [[NSDateComponents alloc]init];
comps.year = 2016;
comps.month = 7;
comps.day = 2;
NSDate* date1 = [calendar dateFromComponents:comps1]; //Initialized as July 7, 2016
NSDate* date2 = [calendar dateFromComponents:comps2]; //Initialized as July 2, 2016
Now that the NSDate
s are created, they can be compared:
if ([date1 isEqualToDate:date2]) {
//Here it returns false, as both dates are not equal
}
We can also use the earlierDate:
and laterDate:
methods of the NSDate
class:
NSDate *earlierDate = [date1 earlierDate:date2];//Returns the earlier of 2 dates. Here earlierDate will equal date2.
NSDate *laterDate = [date1 laterDate:date2];//Returns the later of 2 dates. Here laterDate will equal date1.
Lastly, we can use NSDate
's compare:
method:
NSComparisonResult result = [date1 compare:date2];
if (result == NSOrderedAscending) {
//Fails
//Comes here if date1 is earlier than date2. In our case it will not come here.
}else if (result == NSOrderedSame){
//Fails
//Comes here if date1 is the same as date2. In our case it will not come here.
}else{//NSOrderedDescending
//Succeeds
//Comes here if date1 is later than date2. In our case it will come here
}