How to determine if an NSDate is today? How to determine if an NSDate is today? ios ios

How to determine if an NSDate is today?


In macOS 10.9+ & iOS 8+, there's a method on NSCalendar/Calendar that does exactly this!

- (BOOL)isDateInToday:(NSDate *)date 

So you'd simply do

Objective-C:

BOOL today = [[NSCalendar currentCalendar] isDateInToday:date];

Swift 3:

let today = Calendar.current.isDateInToday(date)


You can compare date components:

NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];if([today day] == [otherDay day] &&   [today month] == [otherDay month] &&   [today year] == [otherDay year] &&   [today era] == [otherDay era]) {    //do stuff}

Edit:

I like stefan's method more, I think it makes for a cleaner and more understandable if statement:

NSCalendar *cal = [NSCalendar currentCalendar];NSDateComponents *components = [cal components:(NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[NSDate date]];NSDate *today = [cal dateFromComponents:components];components = [cal components:(NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:aDate];NSDate *otherDate = [cal dateFromComponents:components];if([today isEqualToDate:otherDate]) {    //do stuff}

Chris, I've incorporated your suggestion. I had to look up what era was, so for anyone else who doesn't know, it distinguishes between BC and AD. This is probably unnecessary for most people, but it's easy to check and adds some certainty, so I've included it. If you're going for speed, this probably isn't a good method anyway.


NOTE as with many answers on SO, after 7 years this is totally out of date. In Swift now just use .isDateInToday


This is an offshoot to your question, but if you want to print an NSDate with "Today" or "Yesterday", use the function

- (void)setDoesRelativeDateFormatting:(BOOL)b

for NSDateFormatter