Objective-C get date strings in locale


Here's how you get the name of the weekday or month as a string in a specified language (locale) in Objective-C (iphone or ipad development).

Code: (Objective-C)
// the date we want to print
NSDateComponents * datecomps = [[NSDateComponents alloc] init];
[datecomps setDay: 21];
[datecomps setMonth: 6];
[datecomps setYear: 1981];
// all texts always in english
NSLocale * usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"us_EN"];
// there are many types of calendars, "ours" is the Gregorian
NSCalendar * gregCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregCalendar setLocale:usLocale];
// now use the date components to construct a new date according to the gregorian calendar
NSDate * date = [gregCalendar dateFromComponents:datecomps];
// this converts the date to a string
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];

// get the name of the week day
[dateFormatter setDateFormat:@"EEEE"];
NSString * weekDayName = [dateFormatter stringFromDate:date];

// get the name of the month
[dateFormatter setDateFormat:@"MMMM"];
NSString * monthName = [dateFormatter stringFromDate:date];

NSLog(@"I was born on a %@ in %@", weekDayName, monthName);

Remember to release objects as you see fit... Certain lines could be combined, but in general the language is very explicit.

Please note that I'm relatively very new to iPhone and iPad development. In a few months I'll probably look back at this code and laugh. Hard. Right now I can only cry about it (No, seriously, what's wrong with just `dayNames[oDate.getDate()]` in JS?). These blogs are mostly meant for people like me right now starting at the language, trying to do basic things, taking more time than it should.

Hope it helps you :)