I'm looking two do two things:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With