How to get iso2 language code for locale?
I'm getting the iso2 language code this开发者_开发问答 way:
public String getLang(Locale language)
return language.toString().substring(0,2).toLowerCase()
}
Is there better way to do this?
edit: when i use getLanguage, i get an empty string.
What about
public String getLang(Locale language)
return language.getLanguage();
}
Of course, this will only be a iso 639-1 2-lettercode if there is one defined for this language, otherwise it may return a 3-letter code (or even longer).
Your code will give silly results if you have a locale without language code (like _DE
) (mine will then return the empty string, which is a bit better, IMHO). If the locale contains a language code, it will return it, but then you don't need the toLowerCase()
call.
I had the same questions and this is what I found.
If you create the Locale
with the constructor as:
Locale locale = new Locale("en_US");
and then you call getLanguage
:
String language = locale.getLanguage();
The value of language
will be "en_us";
If you create the Locale
with the builder:
Locale locale = new Locale.Builder().setLanguage("en").setRegion("US").build()
Then the value locale.getLanguage()
will return "en".
This is strange to me but it's the way it was implemented.
So this was the long answer to explain that if you want the language code to return a two-letter ISO language you need to use the Java Locale
builder or do some string manipulation.
Your method with substring
works but I would use something like I wrote below to cover instances where the delimiter may be "-" or "_".
public String getLang(Locale language)
String[] localeStrings = (language.split("[-_]+"));
return localeStrings[0];
}
Maybe by calling Locale#getLanguage()
Locale locale = ?; locale.getLanguage();
What about using the toLanguageTag()
method?
Example:
public String getLang(Locale language) {
return language.toLanguageTag();
}
精彩评论