How to get Locale from its String representation in Java? How to get Locale from its String representation in Java? java java

How to get Locale from its String representation in Java?


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.


  1. 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();
  2. 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());
  3. 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.