Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weekday of first day of month

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.

like image 633
Anton Avatar asked Sep 17 '13 21:09

Anton


People also ask

Which is the first day of the week?

The Gregorian calendar, currently used in most countries, is derived from the Hebrew calendar, where Sunday is considered the beginning of the week.

How do you calculate beginning of month?

To find the first day of a month we will calculate the last day of the previous month and add one day.


2 Answers

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

like image 191
Dmitry Zhukov Avatar answered Oct 07 '22 12:10

Dmitry Zhukov


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.

like image 3
Anton Avatar answered Oct 07 '22 14:10

Anton