Reputation: 896
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?
Upvotes: 2
Views: 3198
Reputation: 25903
There are two issues in your code.
First of all, the method to get the format you want is Locale#toLanguageTag(), see this:
System.out.println(Locale.US.toLanguageTag()); // en-US
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.
For a list of valid codes, refer to the ISO standard. Wikipedia also has a nice table:
and here is the entry for USA:
Upvotes: 3