I am aware that DateFormatter
s use both language and region to produce the required strings/content.
And especially reading the documentation it seems that i understood correctly how they are supposed to work.
Locales represent the formatting choices for a particular user, not the user’s preferred language. These are often the same but can be different. For example, a native English speaker who lives in Germany might select English as the language and Germany as the region. Text appears in English but dates, times, and numbers follow German formatting rules. The day precedes the month and a 24-hour clock represents times, as shown in Table 4-1
Then why if i set my mobile with
Preferred System Languages: [Spanish, Italian]
Region: United States
and my app ONLY supports German
a simple (pseudocode)
let df = DateFormatter()
df.string(from: date)`
returns miércoles, 26. sept 2018
? (it's spanish with german region formatting)
Considering that the bundle (and therefore all the strings returned from NSLocalizedString(..)
and relative resources) has chosen the language properly (de
, german), why don't the foundation objects use the same language (and not region) supported and identified by the bundle to produce the needed output and instead they stick to the system ones?
Is there some app-wise configuration i am missing or i really have to override language, locale and region for each Calendar, DateFormatter, NumberFormatter, ecc i need to use? Expecially considering how inefficient are these classes and their instantiation.
I listed several questions in the comments, and the answers may change my understanding of the question, but assuming the question is just how to make formatters format using the German language as spoken in Germany, that's just setting a Locale.
let locale = Locale(identifier: "de-DE")
let df = DateFormatter()
df.dateStyle = .full
df.locale = locale
df.string(from: Date()) // "Freitag, 28. September 2018"
The fact that my current Locale is en-US doesn't impact that.
It doesn't take any longer to create a DateFormatter and assign its Locale than to just create a DateFormatter. It's an extra line of code, but you can wrap that up in an extension if you like (and moreover, you may want to create shared immutable instances if you want to avoid creating them repeatedly, but that is true whether you set an explicit Locale or not).
The whole point of things like dateStyle
is that it adapts to the user's configuration. If you don't want to adapt to the user's configuration, just configure the formatters to behave the way you want them to.