views:

1715

answers:

3

I'm looking two do two things:

  1. Check if a week has gone by (based on the day of the week)
  2. Check if a day has gone by (based on the date)

I'm not sure what the best way to solve this is, since when comparing two NSDates (one at 1/1/09 at 21:30 and another at 1/2/09 at 00:30) I can't just see if 24 hours has gone by since in this case it hasn't. I can solve this by just getting the date 1/1/09 from the NSDate, but I'm unsure how to do this based on the documentation and google links that I saw.

For the other issue, I don't know how to know what day of the week it is given a date. I'd like to if 1/1/09 is a Tuesday, Monday, etc... Is there any library that let's you calculate this? This obviously needs to take into account leap years and a tons of other stuff... Maybe there's an objective-c library for this?

Thanks for any help!

A: 

I Think both are solvable with:

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

http://bit.ly/qeveT

"NSTimeInterval is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years."

http://bit.ly/BdOl3

There are 60*60*24=86400 seconds in 24hrs, gives 86400*7=604800 seconds in a week.

monowerker
The interval between two days isn't 24 hours when you switch between daylight savings time and standard time. It's 22 hours on the day you switch the clock forward and 26 hours when you move the clock back. Using an interval is not a good solution.
progrmr
+6  A: 

You can use NSDateComponents for this:

unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:units fromDate:date];

then you can access individual parts of the date like this:

[components year];
[components month];
[components day];

Or, you can construct a new NSDate object using NSCalendar's dateFromComponents method, and compare the two NSDate objects.

Can Berk Güder
+5  A: 

You can use components:fromData: message of the NSCalendar class to get the individual date components:

// Sunday = 1, Saturday = 7
int weekday = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:theDate] weekday];

To compare two dates, just use the compare: message:

switch([date1 compare:date2])
{
case NSOrderedSame:       /* they are the same date */ break;
case NSOrderedAscending:  /* date1 precedes date2 */ break;
case NSOrderedDescending: /* date2 precedes date1 */ break;
}
Adam Rosenfield