I have this category added to NSDate:
- (bool)isWeekend
{
NSString* s = [self asString:@\"e\"];
if ([s isEqual:@\"6\"])
return YES;
else if ([s is
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).
In Swift:
func isWeekend(date: NSDate) -> Bool {
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
return calendar.isDateInWeekend(date)
}
In Swift 3+:
extension Date {
var isWeekend: Bool {
return NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!.isDateInWeekend(self)
}
}
As of iOS 8, you can use isDateOnWeekend:
on NSCalendar
.