Objective-C Language NSDate Date Comparison

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

There are 4 methods for comparing NSDates 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 NSDates 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
    }


Got any Objective-C Language Question?