Detecting if NSDate contains a weekend day

后端 未结 4 1079
南笙
南笙 2021-01-01 20:05

I have this category added to NSDate:

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

  if ([s isEqual:@\"6\"])
    return YES;
  else if ([s is         


        
相关标签:
4条回答
  • 2021-01-01 20:10

    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).

    0 讨论(0)
  • 2021-01-01 20:12

    In Swift:

    func isWeekend(date: NSDate) -> Bool {
        let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        return calendar.isDateInWeekend(date)
    }
    
    0 讨论(0)
  • 2021-01-01 20:29

    In Swift 3+:

    extension Date {
      var isWeekend: Bool {
        return NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!.isDateInWeekend(self)
      }
    }
    
    0 讨论(0)
  • 2021-01-01 20:32

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

    0 讨论(0)
提交回复
热议问题