Search code examples
javalocaleiso-3166

Java Locale to country codes (ISO 3166)


I have an instance of Locale, for example:

Locale l = new Locale("en", "USA");

Now, I want to get the locale in the ISO 3166 format en-US. When I toString it though, I only get en_USA but not en-US.

How to do this correctly?


Solution

  • There are two issues in your code.

    How to get the correct format?

    First of all, the method to get the format you want is Locale#toLanguageTag(), see this:

    System.out.println(Locale.US.toLanguageTag()); // en-US
    

    Why does USA not work?

    Second, the region/country you provided in your constructor, USA, is not a valid region/country according to the ISO. The constructor hence simply ignored it. The correct region is "US", then it also works:

    System.out.println(new Locale("en", "US").toLanguageTag()); // en-US
    

    See the javadoc of the constructor:

    country - An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code. See the Locale class description about valid country values.

    For details, refer to the excellent documentation of the class, it is very detailed.


    Valid codes

    For a list of valid codes, refer to the ISO standard. Wikipedia also has a nice table:

    ISO language codes table

    and here is the entry for USA:

    usa entry