iPhone Developer Tips Visitor Stats: 126,691 Pageviews and 94,296 visitors in the past 30 days.
|
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:

More on Date Formatting:
Date Formatter Examples – Take 1: NSDateFormatter
Date Formatter Examples – Take 2: Format Strings
Date Formatter Examples – Take 3: Date from String
Share with iOS Developers:
Comments
One Response to “Date Formatter Examples – Take 4: Setting Locale”
Leave Comment
The Japanese example is not a good one because the date format in Japan is usually yyyy年mm月dd日.
To truly set the formatter such that it’s aware of the locale (instead of just translating the name of the month), you must use [formatter setDateStyle:].