Weekday of first day of month

拈花ヽ惹草 提交于 2019-12-07 06:58:11

问题


I need to get the weekday of the first day of the month. For example, for the current month September 2013 the first day falls on Sunday.


回答1:


At first, get the first day of current month (for example):

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

Then use NSDateFormatter to print it as a weekday:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];  
[dateFormatter setDateFormat:@"EEEE"]; 
NSLog(@"%@", [dateFormatter stringFromDate:firstDayOfMonth]);

P.S. also take a look at Date Format Patterns




回答2:


Here is the solution to getting the weekday name of the first day in the current month

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

For the weekday index, use this

NSDate *weekDate = [calendar.currentCalendar dateFromComponents:weekdayComps];
NSDateComponents *components = [calendar.currentCalendar components: NSWeekdayCalendarUnit fromDate: weekDate];
NSUInteger weekdayIndex = [components weekday];
NSLog(@"WEEKDAY INDEX %i", weekdayIndex);

You can also increment or decrement the month if needed.




回答3:


Depending on the output you need you may use NSDateFormatter (as it was already said) or you may use NSDateComponents class. NSDateFormatter will give you a string representation, NSDateComponents will give you integer values. Method weekday may do what you want.

NSDateComponents *components = ...;
NSInteger val = [components weekday];



回答4:


For Swift 4.2

First:

extension Calendar {
    func startOfMonth(_ date: Date) -> Date {
        return self.date(from: self.dateComponents([.year, .month], from: date))!
    }
}

Second:

self.firstWeekDay = calendar.component(.weekday, from: calendar.startOfMonth(Date()))


来源:https://stackoverflow.com/questions/18860241/weekday-of-first-day-of-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!