Is there a neat way of getting a Locale instance from its \"programmatic name\" as returned by Locale\'s toString()
method? An obvious and ugly solution would b
Java provides lot of things with proper implementation lot of complexity can be avoided. This returns ms_MY.
String key = "ms-MY";
Locale locale = new Locale.Builder().setLanguageTag(key).build();
Apache Commons has LocaleUtils
to help parse a string representation. This will return en_US
String str = "en-US";
Locale locale = LocaleUtils.toLocale(str);
System.out.println(locale.toString());
You can also use locale constructors.
// Construct a locale from a language code.(eg: en)
new Locale(String language)
// Construct a locale from language and country.(eg: en and US)
new Locale(String language, String country)
// Construct a locale from language, country and variant.
new Locale(String language, String country, String variant)
Please check this LocaleUtils and this Locale to explore more methods.
Well, I would store instead a string concatenation of Locale.getISO3Language()
, getISO3Country()
and getVariant() as key, which would allow me to latter call Locale(String language, String country, String variant)
constructor.
indeed, relying of displayLanguage implies using the langage of locale to display it, which make it locale dependant, contrary to iso language code.
As an example, en locale key would be storable as
en_EN
en_US
and so on ...
Option 1 :
org.apache.commons.lang3.LocaleUtils.toLocale("en_US")
Option 2 :
Locale.forLanguageTag("en-US")
Please note Option 1 is "underscore" between language and country , and Option 2 is "dash".
Method that returns locale from string exists in commons-lang library:
LocaleUtils.toLocale(localeAsString)
Since Java 7 there is factory method Locale.forLanguageTag
and instance method Locale.toLanguageTag
using IETF language tags.
If you are using Spring framework in your project you can also use:
org.springframework.util.StringUtils.parseLocaleString("en_US");
Documentation:
Parse the given String representation into a Locale