Search code examples
javalocale

Locale - two argument construct in action


Here's my code snippet for Locale classes used for date formatting:

List<Locale> locales = new ArrayList<>(8);
locales.add(new Locale("en"));
locales.add(new Locale("pl"));
locales.add(new Locale("en", "PL"));
locales.add(new Locale("en", "CH"));
locales.add(new Locale("en", "BR"));
locales.add(new Locale("pl", "JP"));
locales.add(new Locale("pl", "GER"));
locales.add(new Locale("pl", "DK"));
DateFormat dateInstance;
for (Locale locale : locales) {
    dateInstance = DateFormat.getDateInstance(DateFormat.FULL, locale);
    System.out.println(dateInstance.format(date));
}

I got following output:

Tuesday, April 19, 2016
wtorek, 19 kwietnia 2016
Tuesday, April 19, 2016
Tuesday, April 19, 2016
Tuesday, April 19, 2016
wtorek, 19 kwietnia 2016
wtorek, 19 kwietnia 2016
wtorek, 19 kwietnia 2016

I can't understand what for the constructor's second argument stands for. Mentioned formatted dates aren't dependent on the fact whether I passed the "Country" argument to constructor or not.

...so my question is:

Are there any proper usecases for two-argument Locale constructor?


Solution

  • Yes, there are some cases. Locale is not only used from DateFormat, you can also use it at formatting currencies.

    double amount =200.0;
    Locale locale = new Locale("es", "ES");      
    NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
    System.out.println(currencyFormatter.format(amount));
    
    locale = new Locale("es", "cu");      
    currencyFormatter = NumberFormat.getCurrencyInstance(locale);
    System.out.println(currencyFormatter.format(amount));
    

    In this example the Locales for Spain and for Cuba are defined and 200.00 will be formatted.

    $ java HelloWorld 
    200,00 €
    CU$200,00
    

    As you can see the currency symbol and the position of the currency symbol is changed.