Is there an easier / better way to do this than get NSDateComponents and compare day / month / year?
Yes there is an easier way
-[NSCalendar rangeForUnit:startDate:interval:forDate:] These methods make it easy to set the date at the beginning of the unit (day, hour, month, year, ...) and get the length (interval) of this device.
As a category, it can be used as
@interface NSDate (Comparison) -(BOOL) isSameDay:(NSDate *)rhs; @end @implementation NSDate (Comparison) -(BOOL)isSameDay:(NSDate *)rhs { NSDate *lhs = self; NSDate *lhsStart; NSDate *rhsStart; NSCalendar *cal = [NSCalendar currentCalendar]; [cal rangeOfUnit:NSCalendarUnitDay startDate:&lhsStart interval:NULL forDate:lhs]; [cal rangeOfUnit:NSCalendarUnitDay startDate:&rhsStart interval:NULL forDate:rhs]; return [lhsStart compare:rhsStart] == NSOrderedSame; } @end
This category should work for all versions of iOS and Mac OS X 10.5 +.
for iOS 8+ and Mac OS X 10.9+ you can use NSCalendars
- (BOOL)isDate:(NSDate *)date1 equalToDate:(NSDate *)date2 toUnitGranularity:(NSCalendarUnit)unit;
vikingosegundo Mar 08 '15 at 0:02 2015-03-08 00:02
source share