Home > Blockchain >  DisplayedLanguage to languageTag using Locale?
DisplayedLanguage to languageTag using Locale?

Time:04-19

I use Locale and have displayed language in String, for example "English". Is it possible to convert it to language tag(en)?

CodePudding user response:

The method Locale.getLanguage gives it

Locale l = Locale.ENGLISH;
System.out.println(l.getLanguage()); // en

CodePudding user response:

tl;dr

No, localized names of languages are not mapped back to the standardized language code.

Language code leads to localized language name, but not vice versa.

Localized output, not input

Use localized text such as "English" for presentation to user only, not as key data.

We have international standards for precisely identifying human languages and cultures such as en for English & US for United States culture — use those as key data for purposes such as obtaining a Locale object.

For example:

  • "English" (the word “English” in English)
  • "anglais" (the word “English” in French)
  • "անգլերեն" (the word “English” in Armenian)

… are outputs, not inputs.

This is the difference between Locale#getLanguage and Locale#getDisplayLanguage. The first returns a code while the second returns a localized name of that language. Ditto for Locale#getCountry and Locale#getDisplayCountry.

For fun, let's look at all possible names for “English”.

for ( Locale locale : Locale.getAvailableLocales() )
{
    System.out.println( Locale.US.getLanguage()   " ➜ "   Locale.US.getDisplayLanguage( locale )   " in locale: "   locale.getDisplayName( Locale.US ) );
}

See this code run live at IdeOne.com.

Here is the partial results, truncated per the limit of an Answer's size in Stack Overflow.

en ➜ English in locale: 
en ➜ אנגלית in locale: Hebrew
en ➜ อังกฤษ in locale: Thai (Thai, Thailand)
en ➜ English in locale: Low German
en ➜ iňlis dili in locale: Turkmen (Latin, Turkmenistan)
en ➜ እንግሊዝ in locale: Tigrinya (Ethiopia)
en ➜ ஆங்கிலம் in locale: Tamil (Singapore)
en ➜ angļu in locale: Latvian
en ➜ English in locale: English (Niue)
en ➜ 英语 in locale: Chinese (Simplified, Singapore)
en ➜            
  • Related