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
2009-06-09 05:51:43
That checks for 24 hours, not if its the same date
dizy
2009-06-09 06:08:00
Your answer is wrong (the question asks for calendar days, not time intervals). Please read the question carefully before telling somebody to rtfm!
Christoph
2009-07-25 07:57:34
+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
2009-06-09 06:24:09
perfect, thanks!!! Looking at the code, I won't beat myself up over not being able to get it on my own :)
dizy
2009-06-09 06:36:47