5

我需要得到该月第一天的工作日。例如,对于当前月份 2013 年 9 月,第一天是星期日。

4

4 回答 4

10

首先,获取当前月份的第一天(例如):

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]);

PS 也看看Date Format Patterns

于 2013-09-17T21:48:53.820 回答
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);

如果需要,您还可以增加或减少月份。

于 2013-09-20T22:24:12.667 回答
1

根据您需要的输出,您可以使用NSDateFormatter(如前所述)或者您可以使用NSDateComponentsclass. NSDateFormatter会给你一个字符串表示,NSDateComponents会给你整数值。方法weekday可以做你想做的事。

NSDateComponents *components = ...;
NSInteger val = [components weekday];
于 2013-09-17T21:52:06.100 回答
0

对于斯威夫特 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()))
于 2019-04-05T18:18:03.120 回答