Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateformatter setDateFormat according to currentLocale

I'm going mad with, probably, a stupid problem.

I have 3 strings: year, month and day. I need to have a date in the right format based on currentLocale, so i.e. if currentLocale localeIdentifier is en_US my dateFormat should be: MMM/dd/yyyy

if it's fr_FR the dateFormat should be dd/MMM/yyyy

I don't think the only way to do this is to get currentLocale localeIdentifier and start with a bunch of if then.

Thanks in advance.

Max

like image 913
masgar Avatar asked May 09 '11 15:05

masgar


People also ask

Is NSDateFormatter thread safe?

Thread Safety On earlier versions of the operating system, or when using the legacy formatter behavior or running in 32-bit in macOS, NSDateFormatter is not thread safe, and you therefore must not mutate a date formatter simultaneously from multiple threads.

What is dateFormatter?

A formatter that converts between dates and their textual representations.

What is en_US_POSIX?

In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences.


1 Answers

In Swift 3:

let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
formatter.locale = Locale.current
let date = Date()
let dateString = formatter.string(from: date)
print(dateString)
like image 162
seb Avatar answered Nov 12 '22 19:11

seb