开发者

Detecting if NSDate contains a weekend day

I have this category added to NSDate:

- (bool)isWeekend
{
  NSString* s = [self asString:@"e"];

  if ([s isEqual:@"6"])
    return YES;
  else if ([s isEqual:@"7"])
    return YES;
  else 
    return NO;
}

Helper function:

- (NSString*)asString:(NSString*)format
{
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:format];
  NSString *formattedDateString = [dateFormatter stringFromDate:self];
  [dateFormatter release];

  return formattedDateString;
}

isWeekend should return YES if it is a saturday or a sunday. But it does not work if the locale has a week start on a sunday, in which case friday will be day 6 and saturday will be day 7.

How 开发者_运维百科can I solve this?


You want to use NSCalendar and NSDateComponents:

NSDate *aDate = [NSDate date];
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
  NSLog(@"weekend!");
}

This is operating under the assumption that the first and last days of the week comprise the "week ends" (which is true for the Gregorian calendar. It may not be true in other calendars).


As of iOS 8, you can use isDateOnWeekend: on NSCalendar.


In Swift 3+:

extension Date {
  var isWeekend: Bool {
    return NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!.isDateInWeekend(self)
  }
}


In Swift:

func isWeekend(date: NSDate) -> Bool {
    let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    return calendar.isDateInWeekend(date)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜