Date Formatter: Setting Locale

A reader recently wrote and asked how to show a date output in a different language. By default, the NSDateFormatter will use the locale set on the device, so no code specific locale changes are required if you want your app to display in the current locale.

However, if you need to display a date in a locale other than the current setting on the device, here’s how to do it:

// Create date object  
NSDate *date = [NSDate date];

// Create date formatter
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];

// Set the locale as needed in the formatter (this example uses Japanese)
[dateFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"]
    autorelease]];

// Create date string from formatter, using the current date
NSString *dateString = [dateFormat stringFromDate:date];  

// We're done with this now
[dateFormat release];

// Show that the locale on the device is still set to US 
NSLocale *locale = [NSLocale currentLocale];
NSLog(@"Current Locale: %@", [locale localeIdentifier]);

// Display the date string in format we set above
NSLog(@"Date: %@:", dateString);

The output from the code above looks as follows:

(Source: http://iphonedevelopertips.com/cocoa/date-formatter-examples-take-4-setting-locale.html)



Leave a comment