使用本周和周末检查2个NSDates

时间:2011-05-16 03:13:33

标签: iphone objective-c nsdate

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

Detecting if NSDate contains a weekend day

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

1 个答案:

答案 0 :(得分: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!");
}