简体   繁体   中英

How to check what day of the week it is (i.e. Tues, Fri?) and compare two NSDates?

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!

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM