Thursday, June 13, 2013

NSCalendar setLocale example in Objective C (iOS).


NSCalendar setLocale

Sets the locale for the receiver.

- (void)setLocale:(NSLocale *)locale

Parameters of [NSCalendar setLocale]
locale
The locale for the receiver.

NSCalendar setLocale example.
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setLocale:[NSLocale currentLocale]];

Example of [NSCalendar setLocale].
NSLocale *uk = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
NSCalendar *cal = [NSCalendar currentCalendar];
[cal setLocale:uk];
[uk release];
[myDatePicker setCalendar:cal];

NSCalendar setLocale example.
NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]]; // force US locale, because other countries (e.g. the rest of the world) might use different weekday numbering

NSDateComponents *nowComponents = [calendar components:NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];

[nowComponents setWeekday:1]; //Sunday
[nowComponents setHour:0]; // 12:00 AM = midnight (12:00 PM would be 12)
[nowComponents setMinute:0];
[nowComponents setSecond:0];

NSDate *previousSunday = [calendar dateFromComponents:nowComponents];

End of NSCalendar setLocale example article.