2

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?

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Deepesh kumar Gupta
  • 884
  • 2
  • 11
  • 29
  • `Locale#toLanguageTag()` https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Locale.html#toLanguageTag() – Zabuzard Nov 12 '21 at 10:31
  • 1
    I don't think `USA` is a valid country/region code at all. In the link posted by Zabuzard, it is explicitly stated that this input is invalid: *"Country: If country is not well-formed (for example "12" or "USA"), it will be omitted."* – MC Emperor Nov 12 '21 at 10:34
  • Yeah, the syntax for region has to be valid according to the ISO, see the constructor details and the javadoc of the whole class in general: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Locale.html#%3Cinit%3E(java.lang.String,java.lang.String) – Zabuzard Nov 12 '21 at 10:35

1 Answers1

2

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

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • Agree USA isn't a valid code but some place we use three letter code and my case it is three letter all the time. So we can't get USA to US – Deepesh kumar Gupta Nov 12 '21 at 10:55
  • Well, that is a different question then though. And you should probably elaborate a bit, for example which standard you are following for the 3-letter thing. For example `GER` for `Germany`? What about `France`? `FRA`? And what about regions instead of just countries? Anyways, too much for this comment section. Id suggest you open a new question on SO instead, with all the details. – Zabuzard Nov 12 '21 at 10:59