NSCalendar isDate:equalToDate:toUnitGranularity:

During the beta releases of iOS 7 there were several mentions of a couple of new functions on NSCalendar.

- (BOOL)isDate:(NSDate *)date1 equalToDate:(NSDate *)date2 toUnitGranularity:(NSCalendarUnit)granularity;
- (NSComparisonResult)compareDate:(NSDate *)date1 toDate:(NSDate *)date2 toUnitGranularity:(NSCalendarUnit)granularity;

When I first saw these it was awesome. It makes comparing dates a hell of a lot easier and puts a lot of maths in to one line of code.

The usage is along the lines of...

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

BOOL datesAreEqual = [calendar isDate:firstDate equalToDate:secondDate toUnitGranularity:NSDayCalendarUnit];

datesAreEqual would then be YES for dates on the same day. Not necessarily the same hour, minute or second, etc...

HOWEVER

When the GM of iOS 7 went live, Apple seemingly removed these functions. ::sad face::

Anyway, I've implemented my own version which works in pretty much exactly the same way.

It's a category on NSCalendar.

The header just has the functions.

#import <Foundation/Foundation.h>

@interface NSCalendar (equalWithGranularity)

- (BOOL)ojf_isDate:(NSDate *)date1 equalToDate:(NSDate *)date2 withGranularity:(NSCalendarUnit)granularity;
- (NSComparisonResult)ojf_compareDate:(NSDate *)date1 toDate:(NSDate *)date2 withGranularity:(NSCalendarUnit)granularity;

@end

You can get it on GitHub.

It will also be available shortly through CocoaPods.

Feel free to add it in to your projects.

2 Comments

  1. Yuri Kotov

    Thanks for sharing knowledge about such handy method.

    Two minor comments:

    1. The whole componentFlagsWithGranularity: method can be replaced by int componentFlags = granularity * 2 - 2;

    2. Maybe it would be better to wrap this logic around compare: instead of isEqualToDate: which gives a bit more flexibility? Here is the example.

  2. oliverfoggin

    Thanks for the comment. Apple actually created two functions that they then removed.

    1. isDate:equalToDate:
    2. compareDate:toDate:

    I have now updated the code and added in both of these and also made a cocoa pod for the functions.

Leave a Reply

Your email address will not be published. Required fields are marked *