Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter Locale

How to set Locale for NSDateFormatter? I've tried the below code and its not working.

- (NSString *)localizedStringWithFormat:(NSString *)format {

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:format];
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier: @"fr_FR"];
    cal.locale = locale;
    df.calendar = cal;
    return [df stringFromDate:self];
}

Please let me know how to make this work.

Thanks.

like image 737
arunit21 Avatar asked Sep 23 '13 16:09

arunit21


People also ask

What is en_US_POSIX locale?

en_US_POSIX was invented to refer to the C (or 'null') locale code used in POSIX libraries. It's basically American English, with some peculiarities.

Is NSDateFormatter thread safe?

Thread SafetyOn iOS 7 and later NSDateFormatter is thread safe. In macOS 10.9 and later NSDateFormatter is thread safe so long as you are using the modern behavior in a 64-bit app.

What format is my date in?

The United States is one of the few countries that use “mm-dd-yyyy” as their date format–which is very very unique! The day is written first and the year last in most countries (dd-mm-yyyy) and some nations, such as Iran, Korea, and China, write the year first and the day last (yyyy-mm-dd).

What is en_US_POSIX in iOS?

"en_US_POSIX" is also invariant in time (if the US, at some point in the future, changes the way it formats dates, "en_US" will change to reflect the new behaviour, but "en_US_POSIX" will not), and between machines ("en_US_POSIX" works the same on iOS as it does on OS X, and as it it does on other platforms).


3 Answers

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] 
                     initWithLocaleIdentifier:@"he"];
[dateFormatter setLocale:locale];
like image 171
Niralp Avatar answered Sep 25 '22 00:09

Niralp


in case someone will look for Swift 3 solution:

let dateFormatter = DateFormatter()
let frLocale = Locale(identifier: "fr")
dateFormatter.locale = frLocale
like image 34
Tung Fam Avatar answered Sep 23 '22 00:09

Tung Fam


A bit late to the party, but this is what I did in Swift today:

let df = NSDateFormatter()
df.locale = NSLocale.currentLocale()
df.timeStyle = .MediumStyle
df.dateStyle = .MediumStyle
println("Date: \(df.stringFromDate(obj.dateSent!))")

Depending on your OS region settings, the output should look like this (I'm in Germany):

Date: 27.11.2014 12:30:39

Note: Just figured a lot more people stumble across this SO question, so I guess it can't hurt to answer.

like image 37
BastiBen Avatar answered Sep 26 '22 00:09

BastiBen