How to specify locale in Swift

Issue #578

Locale

Read Language and Locale IDs

1
2
zh-Hans_HK
[language designator]-[script designator]_[region designator]

Language IDs

A language ID identifies a language used in many regions, a dialect used in a specific region, or a script used in multiple regions. To specify a language used in many regions, use a language designator by itself. To specify a specific dialect, use a hyphen to combine a language designator with a region designator. To specify a script, combine a language designator with a script designator. For example, to specify common English, use the en language designator as the language ID. To specify the English language as it is used in the United Kingdom, use en-GB as the language ID.

Locale IDs

A locale ID identifies a specific region and its cultural conventions—such as the formatting of dates, times, and numbers. To specify a locale, use an underscore character to combine a language ID with a region designator, as shown in Table B-5. For example, the locale ID for English-language speakers in the United Kingdom is en_GB, while the locale for English-speaking residents of the United States is en_US.

Example

1
2
3
4
5
6
7
8
9
10
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
formatter.locale = Locale.current

10. jan. 2018, 16:50 // nb_NO
10. jan. 2018, 16:50 // nb_US iOS 12
10. jan. 2018, 4:50 pm // nb_US iOS 13
10 Jan 2018 at 16:50 // en_NO
Jan 10, 2018 at 4:50 PM // en_US

Date format

Use DateFormatter Style

Example short

Specifies a short style, typically numeric only, such as “11/23/37” or “3:30 PM”.

Example medium

Specifies a medium style, typically with abbreviated text, such as “Nov 23, 1937” or “3:30:32 PM”.

From template

If you need to define a format that cannot be achieved using the predefined styles, you can use the setLocalizedDateFormatFromTemplate(_:) to specify a localized date format from a template.

1
2
3
4
5
6
7
8
9
10
11
12
let dateFormatter = DateFormatter()
let date = Date(timeIntervalSinceReferenceDate: 410220000)

// US English Locale (en_US)
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.setLocalizedDateFormatFromTemplate("MMMMd") // set template after setting locale
print(dateFormatter.string(from: date)) // December 31

// British English Locale (en_GB)
dateFormatter.locale = Locale(identifier: "en_GB")
dateFormatter.setLocalizedDateFormatFromTemplate("MMMMd") // // set template after setting locale
print(dateFormatter.string(from: date)) // 31 December

Read more

Comments