How to get Locale from its String representation in Java?
Since Java 7 there is factory method Locale.forLanguageTag
and instance method Locale.toLanguageTag
using IETF language tags.
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_USString 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.