我需要得到这个月第一天的工作日。例如,对于2013年9月的当月,第一天是星期日。
首先,获取当月的第一天(例如):
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:today];
components.day = 1;
NSDate *firstDayOfMonth = [gregorian dateFromComponents:components];
然后使用NSDateFormatter将其打印为工作日:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSLog(@"%@", [dateFormatter stringFromDate:firstDayOfMonth]);
附:还看看Date Format Patterns
以下是获取当月第一天工作日名称的解决方案
NSDateComponents *weekdayComps = [[NSDateComponents alloc] init];
weekdayComps = [calendar.currentCalendar components:calendar.unitFlags fromDate:calendar.today];
weekdayComps.day = 1;
NSDateFormatter *weekDayFormatter = [[NSDateFormatter alloc]init];
[weekDayFormatter setDateFormat:@"EEEE"];
NSString *firstweekday = [weekDayFormatter stringFromDate:[calendar.currentCalendar dateFromComponents:weekdayComps]];
NSLog(@"FIRST WEEKDAY: %@", firstweekday);
对于工作日索引,请使用此选项
NSDate *weekDate = [calendar.currentCalendar dateFromComponents:weekdayComps];
NSDateComponents *components = [calendar.currentCalendar components: NSWeekdayCalendarUnit fromDate: weekDate];
NSUInteger weekdayIndex = [components weekday];
NSLog(@"WEEKDAY INDEX %i", weekdayIndex);
如果需要,您还可以增加或减少月份。
根据您需要的输出,您可以使用NSDateFormatter
(如前所述)或者您可以使用NSDateComponents
类。 NSDateFormatter
会给你一个字符串表示,NSDateComponents
会给你整数值。方法weekday
可以做你想要的。
NSDateComponents *components = ...;
NSInteger val = [components weekday];
对于Swift 4.2
第一:
extension Calendar {
func startOfMonth(_ date: Date) -> Date {
return self.date(from: self.dateComponents([.year, .month], from: date))!
}
}
第二:
self.firstWeekDay = calendar.component(.weekday, from: calendar.startOfMonth(Date()))