views:

204

answers:

2

Could someone please help me figure out how to check if some date is of the same day as today. I guess it would require creating a calender day at 0 hour of the same day in the same timezone and checking against that, but so far my attempts have confused me more then anything.

A: 

You should take a good read through this Dates and Times Programming Topics for Cocoa, but something like this should work:

NSDate *today = [NSDate date];
NSTimeInterval difference = [today timeIntervalSinceDate:otherDate];
NSTimeInterval secondsPerDay = 24 * 60 * 60;
if (difference < secondsPerDay)
{
   //same day as today
}
Nick Stamas
That checks for 24 hours, not if its the same date
dizy
Your answer is wrong (the question asks for calendar days, not time intervals). Please read the question carefully before telling somebody to rtfm!
Christoph
+2  A: 

NSCalendar lets you deal with human days. So you could implement a category something like this:

@implementation NSDate (IsItToday)
- (BOOL)isToday {
    NSUInteger desiredComponents = NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
    NSDateComponents *myCalendarDate = [[NSCalendar currentCalendar] components:desiredComponents fromDate:self];
    NSDateComponents *today = [[NSCalendar currentCalendar] components:desiredComponents fromDate:[NSDate date]];
    return [myCalendarDate isEqual:today];
}
@end
Chuck
perfect, thanks!!! Looking at the code, I won't beat myself up over not being able to get it on my own :)
dizy