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?
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?
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:
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:See the javadoc of the constructor:
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:
and here is the entry for USA: