How to get iso2 language code for locale?

I get the iso2 language code this way:

public String getLang(Locale language) return language.toString().substring(0,2).toLowerCase() } 

Is there a better way to do this?

edit : when I use getLanguage, I get an empty string.

+8
java locale
source share
4 answers

What about

 public String getLang(Locale language) return language.getLanguage(); } 

Of course, it will only be a 2-letter code iso 639-1, if it is defined for this language, otherwise it can return a 3-letter code (or even more).


Your code will give silly results if you have a locale without a language code (for example, _DE ) (mine will return an empty string, which is slightly better, IMHO). If the locale contains a locale code, it will return it, but then you do not need toLowerCase() call.

+11
source share

I had the same questions, and this is what I found.

If you create a Locale with a constructor like:

 Locale locale = new Locale("en_US"); 

and then you call getLanguage :

 String language = locale.getLanguage(); 

The language value will be "en_us";

If you create a Locale using the builder:

 Locale locale = new Locale.Builder().setLanguage("en").setRegion("US").build() 

Then the value of locale.getLanguage() will return, it will be "en".

This is strange for me, but it was implemented that way.

So, this was a long answer to explain that if you want the language code to return the two-letter ISO language, you need to use the Java Locale constructor or do some string manipulation.

Your substring method works, but I would like to use something like the one below to cover cases where the delimiter can be "-" or "_".

 public String getLang(Locale language) String[] localeStrings = (language.split("[-_]+")); return localeStrings[0]; } 
+2
source share

Perhaps calling Locale#getLanguage()

0
source share

Locale locale = ?; locale.getLanguage();

0
source share

All Articles