How to get Locale from its String representation in Java?

前端 未结 12 1037
慢半拍i
慢半拍i 2020-12-08 00:06

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

相关标签:
12条回答
  • 2020-12-08 00:12
    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.

    0 讨论(0)
  • 2020-12-08 00:14

    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 ...

    0 讨论(0)
  • 2020-12-08 00:16

    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".

    0 讨论(0)
  • 2020-12-08 00:22

    Method that returns locale from string exists in commons-lang library: LocaleUtils.toLocale(localeAsString)

    0 讨论(0)
  • 2020-12-08 00:24

    Since Java 7 there is factory method Locale.forLanguageTag and instance method Locale.toLanguageTag using IETF language tags.

    0 讨论(0)
  • 2020-12-08 00:27

    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

    0 讨论(0)
提交回复
热议问题