Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if NSDate contains a weekend day

Tags:

objective-c

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?

like image 748
Kobski Avatar asked Mar 24 '11 22:03

Kobski


4 Answers

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

like image 165
Dave DeLong Avatar answered Oct 23 '22 07:10

Dave DeLong


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

like image 39
benkraus Avatar answered Oct 23 '22 08:10

benkraus


In Swift 3+:

extension Date {
  var isWeekend: Bool {
    return NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!.isDateInWeekend(self)
  }
}
like image 37
Federico Zanetello Avatar answered Oct 23 '22 07:10

Federico Zanetello


In Swift:

func isWeekend(date: NSDate) -> Bool {
    let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    return calendar.isDateInWeekend(date)
}
like image 24
mbonness Avatar answered Oct 23 '22 07:10

mbonness