Thursday, June 13, 2013

NSCalendar setFirstWeekday example in Objective C (iOS).

NSCalendar setFirstWeekday

Sets the index of the first weekday for the receiver.

- (void)setFirstWeekday:(NSUInteger)weekday

Parameters of [NSCalendar setFirstWeekday]
The first weekday for the receiver.

NSCalendar setFirstWeekday example.
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);

Example of [NSCalendar setFirstWeekday].
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setFirstWeekday:5]; // 5 = Thursday, 1 = Sunday, 2 = Monday, etc.

NSCalendar setFirstWeekday example.
NSCalendar *gregorianT = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorianT setFirstWeekday:2];

NSDateFormatter *formatDayWeek = [[NSDateFormatter alloc] init];
[formatDayWeek setCalendar:gregorianT];
[formatDayWeek setDateFormat:@"c EEEE"];

NSLog(@"Value for date: %@", [formatDayWeek stringFromDate:dateForMonth]);
...or you can access the ordinality directly from your NSCalendar object.

NSCalendar *gregorianT = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorianT setFirstWeekday:2];

NSUInteger valueOfDay = [gregorianT ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:dateForMonth];

NSLog(@"Value for date : %ld", (long)valueOfDay);

End of NSCalendar setFirstWeekday example article.