Thursday, June 13, 2013

NSCalendar initWithCalendarIdentifier example in Objective C (iOS).

NSCalendar initWithCalendarIdentifier

Initializes a newly-allocated NSCalendar object for the calendar specified by a given identifier.

- (id)initWithCalendarIdentifier:(NSString *)string

The identifier for the new calendar. For valid identifiers, see NSLocale.

Return Value of [NSCalendar initWithCalendarIdentifier]
The initialized calendar, or nil if the identifier is unknown (if, for example, it is either an unrecognized string or the calendar is not supported by the current version of the operating system).

NSCalendar initWithCalendarIdentifier 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 initWithCalendarIdentifier].
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
NSDateComponents *weekdayComponents =
                    [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
[weekdayComponents setHour:12];
[weekdayComponents setMinute:10];
[weekdayComponents setSeconds:30];

NSCalendar initWithCalendarIdentifier example.
NSDate *startDate = ...;
NSDate *endDate = ...;

NSCalendar *gregorian = [[NSCalendar alloc]

NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags
                                          toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];

End of NSCalendar initWithCalendarIdentifier example article.