How to compare two NSDates

Screen Shot 2014-01-07 at 12.55.39Comparing NSDate objects should be as easy as comparing two numbers. But because NSDate objects are complex, it’s not an easy task.

Lucky for us the NSDate class has several ways of dealing with this conundrum.

Imagine in the following examples that we have the objects “today” and “myDate”, the latter of which we would like to compare to today. We want to know, is myDate earlier or later than today?

earlierDate and laterDate

The easiest two to remember (for me) are earlierDate and laterDate. Here’s how they work:

    if ([myDate laterDate:today] == myDate) {
        NSLog(@"myDate is LATER than today");
    } else {
        NSLog(@"myDate is EARLIER than today");
    }
    
    // likewise:
    if ([myDate earlierDate:today] == myDate) {
        NSLog(@"myDate is EARLIER than today");
    } else {
        NSLog(@"myDate is LATER than today");
    }

laterDate returns the NSDate object which is later, earlierDate returns the earlier one.

compare

For those brains that are wired like a frigging computer we also have the compare method, which compares the results to three much less intuitive enumerations:

    if ([myDate compare:today] == NSOrderedAscending) {
        NSLog(@"myDate is EARLIER than today");
    }
    
    if ([myDate compare:today] == NSOrderedDescending) {
        NSLog(@"myDate is LATER than today");
    }
    
    if ([myDate compare:today] == NSOrderedSame) {
        NSLog(@"myDate and today are THE SAME DATE");
    }

The latter option can be good if you need to make sure the two dates are identical.





Leave a Reply