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.
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.
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.
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).
"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).
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc]
initWithLocaleIdentifier:@"he"];
[dateFormatter setLocale:locale];
in case someone will look for Swift 3 solution:
let dateFormatter = DateFormatter()
let frLocale = Locale(identifier: "fr")
dateFormatter.locale = frLocale
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With