Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 € 
like image 551
Pascal Avatar asked Jul 02 '11 11:07

Pascal


2 Answers

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.

like image 147
JB Nizet Avatar answered Oct 01 '22 01:10

JB Nizet


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
like image 21
Bozho Avatar answered Oct 01 '22 02:10

Bozho