Using this week and weekend to check in between 2 NSDates
The NSDate part of my assignment requires me to display events according t开发者_运维问答o the category the user chooses. The categories are - today, this month, this week, and this weekend. I've done both 'today' and 'this month' and I'm having trouble with the other two. Basically I have a date range for every event (e.g fromDate = 03-04-2011 , toDate = 03-11-2011). What I want to do is check if this week and this weekend falls in between the date range. I've googled for sources but couldn't find what I need. I understand that I have to use the NSCalendar but I don't know how to go about it.
Detecting if NSDate contains a weekend day
^ The answer seems to be what I'm looking for but I have no idea how to use it. Any help on that or any other solution will be appreciated. Thanks
- (BOOL)checkForWeekend:(NSDate *)aDate {
BOOL isWeekendDate = NO;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSRange weekdayRange = [calendar maximumRangeOfUnit:NSWeekdayCalendarUnit];
NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit fromDate:aDate];
NSUInteger weekdayOfDate = [components weekday];
if (weekdayOfDate == weekdayRange.location || weekdayOfDate == weekdayRange.length) {
// The date falls somewhere on the first or last days of the week.
isWeekendDate = YES;
}
return isWeekendDate;
}
USAGE:
BOOL isWeekend = [self checkForWeekend:[NSDate date]]; // Any date can be passed here.
if (isWeekend) {
NSLog(@"Weekend date! Yay!");
}
精彩评论