我需要获得该月第一天的工作日。例如,对于2013年9月的当月,第一天是星期日。
答案 0 :(得分: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]);
P.S。另请查看Date Format Patterns
答案 1 :(得分:3)
以下是获取当月第一天工作日名称的解决方案
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);
如果需要,您还可以增加或减少月份。
答案 2 :(得分:1)
根据您需要的输出,您可以使用NSDateFormatter
(如前所述),或者您可以使用NSDateComponents
课程。 NSDateFormatter
将为您提供字符串表示形式,NSDateComponents
将为您提供整数值。方法weekday
可以做你想做的事。
NSDateComponents *components = ...;
NSInteger val = [components weekday];
答案 3 :(得分:0)
对于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()))