Java Locale create in different ways
In this tutorial we’re going to show how to create Locale using builder, constructors, and factory method for different languages and variants to get localized dates.
In the below examples we’ll use the following helper method, that just prints date formatted according to selected locale:
import java.text.DateFormat; import java.util.Date; import java.util.Locale; import static java.text.DateFormat.DEFAULT; import static java.text.DateFormat.getDateInstance; void printResult(Locale locale) { DateFormat dateFormat = getDateInstance(DEFAULT, locale); String formattedDate = dateFormat.format(new Date()); System.out.printf("Date in %s locale: %s%n", locale, formattedDate); }
Locale constants
For some languages there are predefined Locale constants:
System.out.println("Locales from constants:"); printResult(Locale.CANADA); printResult(Locale.CHINA);
It produces:
Locales from constants: Date in en_CA locale: 6-May-2016 Date in zh_CN locale: 2016-5-6
Locale using constructor
For most languages Locale has to be constructed using constructor:
System.out.println("Locales using constructors:"); // language, country, variant printResult(new Locale("pl")); printResult(new Locale("en", "US")); printResult(new Locale("gr", "GR", "polyton"));
The results are:
Locales using constructors: Date in pl locale: 2016-05-06 Date in en_US locale: May 6, 2016 Date in gr_GR_polyton locale: May 6, 2016
Locale using builder
For more complicated cases or when you want to have more readable parameters use Locale.Builder like here:
System.out.println("Locales using Builder:"); Locale locale = new Locale.Builder() .setLanguage("en").setRegion("GB") .build(); printResult(locale); locale = new Locale.Builder() .setLanguage("zh").setRegion("CN") .build(); printResult(locale); locale = new Locale.Builder() .setLanguage("ru").setScript("Cyrl") .build(); printResult(locale);
The result of applying above locales are:
Locales using Builder: Date in en_GB locale: 06-May-2016 Date in zh_CN locale: 2016-5-6 Date in ru__#Cyrl locale: 06.05.2016
Locale.forLanguageTag() factory method
Finally, there’s also Locale.forLanguageTag() factory method. It has pretty complex syntax:
System.out.println("Locale.forLanguageTag factory method:"); printResult(Locale.forLanguageTag("pl-PL")); printResult(Locale.forLanguageTag("jp-JP-u-ca-japanese"));
It formats dates as follows:
Locale.forLanguageTag factory method: Date in pl_PL locale: 2016-05-06 Date in jp_JP_#u-ca-japanese locale: Heisei 28 May 6
References:
- Check out Java ResourceBundle – internationalized program to see how to mix Locale with ResourceBundle