Day of the week of the first day of the month

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

+5
source share
4 answers

First select the first day of the 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 on a weekday:

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

PS also see Date Format Formats

+9
source

Here is the solution to get the name of the day of the week 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 week week 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); 

If necessary, you can increase or decrease the month.

+3
source

Depending on the output, you can use NSDateFormatter (as already mentioned), or you can use the NSDateComponents class. NSDateFormatter will give you a string representation, NSDateComponents will give you integer values. The weekday method can do what you want.

 NSDateComponents *components = ...; NSInteger val = [components weekday]; 
+1
source

For Swift 4.2

The first:

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

Secondly:

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

Source: https://habr.com/ru/post/1502687/


All Articles