Kobski Kobski - 6 months ago 23
Objective-C Question

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?

Answer

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

Comments