If you have the ISO country code `US`, `FR`, how do you get the Locale code (`Locale.US`, `Locale.FRANCE`)?
Asked Answered
I

5

25

If you have the country code US, FR (ISO-3166-1 alpha-2 country code), how do you get the Locale code (Locale.US, Locale.FRANCE) to do something like this:

System.out.println(DecimalFormat.getCurrencyInstance(Locale.US).format(12.34));
System.out.println(DecimalFormat.getCurrencyInstance(Locale.FRANCE).format(12.34));

$12.34
12,34 €
Injunction answered 2/7, 2011 at 11:44 Comment(0)
B
28

You can't, because a Locale is used to hold a language, not a country. It can hold a language for a specific country, and for a specific variant in this country, but it's a language first. And there is no one-to-one relationship between a language and a country. Most languages are spoken in various countries, and many countries have several languages.

If you had the country code for a language, you could use new Locale(code). But with a country code, all you can do is call getAvailableLocales, loop through the results, and find one which has your country code. But there might be several ones.

Bricole answered 2/7, 2011 at 11:56 Comment(0)
D
7

In Java7 there is the Locale.Builder, but before that there isn't an easy way. You can, however create a utility method:

  1. loop Locale.getAvailableLocales()
  2. for each check if locale.getCountryCode().equals(countryCodeParam) and return it
Descry answered 2/7, 2011 at 11:54 Comment(1)
can Locale.Builder help here to get default language from a countrycode?Calen
D
5

You can either create the locale,

new Locale("en", "US")
new Locale("fr", "FR")

or

iterate through Locale.getAvailableLocales() till you find your locale and then use that instance.

Dost answered 2/7, 2011 at 11:54 Comment(0)
E
2

A locale is specified most importantly by the ISO-639 language code, possible also a ISO-3166 country code and a variant. The Locale class has constructors that take either only a language code, or additionally a country code, or additionally a variant.

If you only have the country code, you first need a map that converts it to a language code - but that does not necessarily produce a unique result, many countries use more than one official language.

Ezechiel answered 2/7, 2011 at 11:55 Comment(0)
M
0

The accepted answer is of course correct, but a solution is still needed. So, here is my attempt to implement it:

   public static Locale countryCodeToLocate(String countryCode) {

        for(Locale l : Locale.getAvailableLocales()) {
            // try to convert `en_US` into `us`
            String lang = l.toString().toLowerCase();
            String prefix = l.getLanguage().toLowerCase();
            if (lang.startsWith(prefix + "_" + countryCode)) {
                return l;
            }
        }
        return Locale.getDefault();
    }
Mcwherter answered 2/3, 2023 at 8:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.