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.

有帮助吗?

解决方案

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

其他提示

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.

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

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()))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top