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.
The getLanguage() method of Locale class in Java is used to get language code for the specified locale. This will either be an empty string or a lowercase ISO 639 code. Parameters: This method does not take any parameters.
Use of LocaleUse getCountry to get the country (or region) code and getLanguage to get the language code. You can use getDisplayCountry to get the name of the country suitable for displaying to the user. Similarly, you can use getDisplayLanguage to get the name of the language suitable for displaying to the user.
A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user.
The getCountry() method of Locale class in Java is used to get the country or region code for the specified locale. This will either be an empty string or an uppercase ISO 3166 2-letter code, or a UN M.
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With