11

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!

rksprst
  • 6,471
  • 18
  • 54
  • 81

2 Answers2

30

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
  • 390,455
  • 97
  • 512
  • 589
13

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
  • 109,922
  • 25
  • 130
  • 137