How to determine if an NSDate is today?
Solution 1:
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)
Solution 2:
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
Solution 3:
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
Solution 4:
I would try to get today's date normalized to midnight and the second date, normalize to midnight then compare if it is the same NSDate.
From an Apple example here's how you normalize to midnight today's date, do the same for the second date and compare:
NSCalendar * gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents * components =
[gregorian components:
(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit)
fromDate:[NSDate date]];
NSDate * today = [gregorian dateFromComponents:components];
Solution 5:
Working Swift 3 & 4 extension of the suggestion by Catfish_Man:
extension Date {
func isToday() -> Bool {
return Calendar.current.isDateInToday(self)
}
}