Seb
Seb

Reputation: 545

NSDate month and week day localized

I'm trying to display a localized date (with the week day and month in letters) depends on the language of the phone (not the region format).

I tried :

// Date formatter
NSDateFormatter* df = [[NSDateFormatter alloc] init];
NSLocale* locale = [NSLocale currentLocale];
NSLog(@"locale : %@", locale.localeIdentifier);
[df setDateFormat:[NSDateFormatter dateFormatFromTemplate:@"EEEE dd MMMM" options:0 locale:[NSLocale currentLocale]]]; 

But when I change the language of the phone, it changes nothing, it still displays in french. How can I make it work ?

Upvotes: 8

Views: 5868

Answers (3)

Felix Lapalme
Felix Lapalme

Reputation: 1068

Use Desdenova's answer to have working code.

To test it (and take screenshots, for example), you'll need to change the device's language AND the region format.

If you only change the device's language, it may change the date a little bit, but the months and days (the names) will still be in the language of the region format.

Upvotes: 0

Nikola Kirev
Nikola Kirev

Reputation: 3152

You are testing it wrong. What you should do is change the Region Format, not the Language of the device.

Go to Settings->General->International->Region Format to change it and test it again.

I hope it helps.

EDIT: Using the Language is not a good idea. iOS is not translated to that many languages. However it supports a lot of region formats.

Example: I live in Bulgaria. iOS is not translated to bulgarian, so the actual menus and apps use English language, but as I have set my Region Format to Bulgaria, all of the date formats, date labels and currency labels are the bulgarian ones.

Upvotes: 1

Desdenova
Desdenova

Reputation: 5378

Try this one;

First we get the device language, then we set the locale of NSDateFormatter with that language.

NSString * deviceLanguage = [[NSLocale preferredLanguages] objectAtIndex:0];
NSDateFormatter * dateFormatter = [NSDateFormatter new];
NSLocale * locale = [[NSLocale alloc] initWithLocaleIdentifier:deviceLanguage];

[dateFormatter setDateFormat:@"EEEE dd MMMM"];
[dateFormatter setLocale:locale];

NSString * dateString = [dateFormatter stringFromDate:[NSDate date]];

NSLog(@"%@", dateString);

Upvotes: 9

Related Questions