How to get Locale from its String representation in Java?

前端 未结 12 1054
慢半拍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.

提交回复
热议问题