且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检测NSDate是否包含周末

更新时间:2023-11-29 16:09:34

您要使用NSCalendarNSDateComponents:

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