How to get Locale from its String representation in Java?

前端 未结 12 1049
慢半拍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:38

    This answer may be a little late, but it turns out that parsing out the string is not as ugly as the OP assumed. I found it quite simple and concise:

    public static Locale fromString(String locale) {
        String parts[] = locale.split("_", -1);
        if (parts.length == 1) return new Locale(parts[0]);
        else if (parts.length == 2
                || (parts.length == 3 && parts[2].startsWith("#")))
            return new Locale(parts[0], parts[1]);
        else return new Locale(parts[0], parts[1], parts[2]);
    }
    

    I tested this (on Java 7) with all the examples given in the Locale.toString() documentation: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "zh_CN_#Hans", "zh_TW_#Hant-x-java", and "th_TH_TH_#u-nu-thai".

    IMPORTANT UPDATE: This is not recommended for use in Java 7+ according to the documentation:

    In particular, clients who parse the output of toString into language, country, and variant fields can continue to do so (although this is strongly discouraged), although the variant field will have additional information in it if script or extensions are present.

    Use Locale.forLanguageTag and Locale.toLanguageTag instead, or if you must, Locale.Builder.

提交回复
热议问题