利用本周和周末在 2 个 NSDate 之间签到



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

检测 NSDate 是否包含周末

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

- (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!");
}

最新更新