How to check if an NSDate
belongs to today?
I used to check it using first 10 characters from [aDate description]
. [[aDate descriptio
My solution is calculate how much days passed since 1970 by division and compare the integer part
#define kOneDay (60*60*24)
- (BOOL)isToday {
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSInteger days =[self timeIntervalSince1970] + offset;
NSInteger currentDays = [[NSDate date] timeIntervalSince1970] + offset;
return (days / kOneDay == currentDays / kOneDay);
}
for iOS7 and earlier:
//this is now => need that for the current date
NSDate * now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone systemTimeZone]];
NSDateComponents * components = [calendar components:( NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate: now];
[components setMinute:0];
[components setHour:0];
[components setSecond:0];
//this is Today's Midnight
NSDate *todaysMidnight = [calendar dateFromComponents: components];
//now timeIntervals since Midnight => in seconds
NSTimeInterval todayTimeInterval = [now timeIntervalSinceDate: todaysMidnight];
//now timeIntervals since OtherDate => in seconds
NSTimeInterval otherDateTimeInterval = [now timeIntervalSinceDate: otherDate];
if(otherDateTimeInterval > todayTimeInterval) //otherDate is not in today
{
if((otherDateTimeInterval - todayTimeInterval) <= 86400) //86400 == a day total seconds
{
@"yesterday";
}
else
{
@"earlier";
}
}
else
{
@"today";
}
now = nil;
calendar = nil;
components = nil;
todaysMidnight = nil;
NSLog("Thank you :-)");
No need to juggle with components, eras and stuff.
NSCalendar provides an method to get the beginning of a certain time unit for an existing date.
This code will get the begin of today and another date and compare that. If it evaluates to NSOrderedSame
, both dates are during the same day — so today.
NSDate *today = nil;
NSDate *beginningOfOtherDate = nil;
NSDate *now = [NSDate date];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&today interval:NULL forDate:now];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&beginningOfOtherDate interval:NULL forDate:beginningOfOtherDate];
if([today compare:beginningOfOtherDate] == NSOrderedSame) {
//otherDate is a date in the current day
}
There is an easier way than many of the above answers!
NSDate *date = ... // The date you wish to test
NSCalendar *calendar = [NSCalendar currentCalendar];
if([calendar isDateInToday:date]) {
//do stuff
}
Working Swift 3 & 4 extension of the suggestion by Catfish_Man:
extension Date {
func isToday() -> Bool {
return Calendar.current.isDateInToday(self)
}
}
If you have a lot of these date comparisons, then the calls to calendar:components:fromDate
start to take up a lot of time. According to some profiling I have done, they seem to be quite expensive.
Say you are trying to determine which from some array of dates, say NSArray *datesToCompare
, are the same day as some given day, say NSDate *baseDate
, then you can use something like the following (partly adapted from an answer above):
NSDate *baseDate = [NSDate date];
NSArray *datesToCompare = [NSArray arrayWithObjects:[NSDate date],
[NSDate dateWithTimeIntervalSinceNow:100],
[NSDate dateWithTimeIntervalSinceNow:1000],
[NSDate dateWithTimeIntervalSinceNow:-10000],
[NSDate dateWithTimeIntervalSinceNow:100000],
[NSDate dateWithTimeIntervalSinceNow:1000000],
[NSDate dateWithTimeIntervalSinceNow:50],
nil];
// determine the NSDate for midnight of the base date:
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* comps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit)
fromDate:baseDate];
NSDate* theMidnightHour = [calendar dateFromComponents:comps];
// set up a localized date formatter so we can see the answers are right!
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
// determine which dates in an array are on the same day as the base date:
for (NSDate *date in datesToCompare) {
NSTimeInterval interval = [date timeIntervalSinceDate:theMidnightHour];
if (interval >= 0 && interval < 60*60*24) {
NSLog(@"%@ is on the same day as %@", [dateFormatter stringFromDate:date], [dateFormatter stringFromDate:baseDate]);
}
else {
NSLog(@"%@ is NOT on the same day as %@", [dateFormatter stringFromDate:date], [dateFormatter stringFromDate:baseDate]);
}
}
Output:
Nov 23, 2011 1:32:00 PM is on the same day as Nov 23, 2011 1:32:00 PM
Nov 23, 2011 1:33:40 PM is on the same day as Nov 23, 2011 1:32:00 PM
Nov 23, 2011 1:48:40 PM is on the same day as Nov 23, 2011 1:32:00 PM
Nov 23, 2011 10:45:20 AM is on the same day as Nov 23, 2011 1:32:00 PM
Nov 24, 2011 5:18:40 PM is NOT on the same day as Nov 23, 2011 1:32:00 PM
Dec 5, 2011 3:18:40 AM is NOT on the same day as Nov 23, 2011 1:32:00 PM
Nov 23, 2011 1:32:50 PM is on the same day as Nov 23, 2011 1:32:00 PM