How to get Locale from its String representation in Java?

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

    See the Locale.getLanguage(), Locale.getCountry()... Store this combination in the database instead of the "programatic name"...
    When you want to build the Locale back, use public Locale(String language, String country)

    Here is a sample code :)

    // May contain simple syntax error, I don't have java right now to test..
    // but this is a bigger picture for your algo...
    public String localeToString(Locale l) {
        return l.getLanguage() + "," + l.getCountry();
    }
    
    public Locale stringToLocale(String s) {
        StringTokenizer tempStringTokenizer = new StringTokenizer(s,",");
        if(tempStringTokenizer.hasMoreTokens())
        String l = tempStringTokenizer.nextElement();
        if(tempStringTokenizer.hasMoreTokens())
        String c = tempStringTokenizer.nextElement();
        return new Locale(l,c);
    }
    

提交回复
热议问题