Question

I'm currently writing an app for the iPhone that heavily works with dates. I'm using NSDateFormatter to convert dates to strings. Conveniently, NSDateFormatter automatically creates strings in the user's language based on the region format. Because I can't localize my app in all possible languages and regions, the app is only localized in English, German, Spanish and a few others.

When the app is running for a French user for example, the app defaults to English. That is fine, but the dates will still be converted using the French language. This results in strings like "Month: Juillet" instead of "Month: July".

How can I make the NSDateFormatter always use the language the app runs in? I know that I could use NSLocalizedString() to localize NSLocale identifiers, but this will yield in incorrect region settings.

When the user usually uses a "en_GB" region and my app is localized for English in general, I want the NSDateFormatter to use "en_GB" and not just "en" or "en_US". When the user runs French, I want the locale to be "en" and if he runs the app in the "de_DE" region, I want the date formats to be "de_DE", too, because the app supports German.

Regards, Fabian

Était-ce utile?

La solution

When you create the date formatter, it initialises it's style from the current locale, but you can override this.

[not tested] You can get the best locale from the users list and your available locale using NSBundle:

+ (NSArray *)preferredLocalizationsFromArray:(NSArray *)localizationsArray

NSFormatter:

+ (NSString *)dateFormatFromTemplate:(NSString *)template options:(NSUInteger)opts locale:(NSLocale *)locale

Should give you a localised format string for the specified locale.

You can then use setDateFormat to override the initial date format for the formatter.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top