Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSCalendar first day of week

Does anyone know if there is a way to set the first day of the week on a NSCalendar, or is there a calendar that already has Monday as the first day of the week, instead of Sunday. I'm currently working on an app that is based around a week's worth of work, and it needs to start on Monday, not Sunday. I can most likely do some work to work around this, but there will be a lot of corner cases. I'd prefer the platform do it for me.

Thanks in advance

Here's some the code that I'm using. it's saturday now, so what I would hope is that weekday would be 6, instead of 7. that would mean that Sunday would be 7 instead of rolling over to 0

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setFirstWeekday:0];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit;
NSDateComponents *todaysDate = [gregorian components:unitFlags fromDate:[NSDate date]];
int dayOfWeek = todaysDate.weekday;
like image 312
Joshua Avatar asked Jul 09 '09 23:07

Joshua


3 Answers

Edit: This does not check the edge case where the beginning of the week starts in the prior month. Some updated code to cover this: https://stackoverflow.com/a/14688780/308315


In case anyone is still paying attention to this, you need to use

ordinalityOfUnit:inUnit:forDate:

and set firstWeekday to 2. (1 == Sunday and 7 == Saturday)

Here's the code:

NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[gregorian setFirstWeekday:2]; // Sunday == 1, Saturday == 7
NSUInteger adjustedWeekdayOrdinal = [gregorian ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:[NSDate date]];
NSLog(@"Adjusted weekday ordinal: %d", adjustedWeekdayOrdinal);

Remember, the ordinals for weekdays start at 1 for the first day of the week, not zero.

Documentation link.

like image 115
Kris Markel Avatar answered Nov 05 '22 12:11

Kris Markel


This code constructs a date that is set to Monday of the current week:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDate *today = [NSDate date];
NSDate *beginningOfWeek = nil;
BOOL ok = [gregorian rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek
                                interval:NULL forDate: today];
like image 31
Kendall Helmstetter Gelner Avatar answered Nov 05 '22 10:11

Kendall Helmstetter Gelner


setFirstWeekday: on the NSCalendar object. Sets the index of the first weekday for the receiver.

- (void)setFirstWeekday:(NSUInteger)weekday

Should do the trick.

like image 12
mmc Avatar answered Nov 05 '22 12:11

mmc