Date Comparison

suggest change

There are 4 methods for comparing NSDates in Objective-C:

Consider two dates, 7 July 2016 and 2 July 2016:

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *comps1 = [[NSDateComponents alloc] init];
comps1.year = 2016;
comps1.month = 7;
comps1.day = 7;

NSDateComponents *comps2 = [[NSDateComponents alloc] init];
comps2.year = 2016;
comps2.month = 7;
comps2.day = 2;

NSDate *date1 = [calendar dateFromComponents:comps1]; // 7 July 2016
NSDate *date2 = [calendar dateFromComponents:comps2]; // 2 July 2016

Now that the NSDates are created, they can be compared:

if ([date1 isEqualToDate:date2]) {
    // Not entered: the 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
    }

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents