2011-05-16 51 views
2

我的任务的NSDate部分要求我根据用户选择的类别显示事件。类别是 - 今天,本月,本周和本周末。我已经做了'今天'和'这个月',而我在其他两个人遇到麻烦。基本上我有每个事件的日期范围(例如,从日期= 03-04-2011,到日期= 03-11-2011)。我想要做的是检查本周和本周末是否在日期范围之间。我已经搜索了来源,但找不到我需要的东西。我知道我必须使用NSCalendar,但我不知道如何去做。使用本周和周末检查两个NSDates

Detecting if NSDate contains a weekend day

^答案似乎正是我要找的,但我不知道如何使用它。对此或任何其他解决方案的任何帮助将不胜感激。由于

回答

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

用法:

BOOL isWeekend = [self checkForWeekend:[NSDate date]]; // Any date can be passed here. 

if (isWeekend) { 
    NSLog(@"Weekend date! Yay!"); 
} 
+0

感谢您的详细答复!有没有办法获得本周末的NSDate?我需要将日期与我的活动日期进行比较,以检查它们是否在两者之间。 – Joe 2011-05-16 06:35:30