How to get Locale from its String view in Java?

Is there a neat way to get a Locale instance from its "program name" returned by the Locale toString() method? An obvious and ugly solution would be to parse String and then create a new Locale instance in accordance with this, but maybe there is a better solution / turnkey solution for this?

It is necessary that I want to save some locale-specific settings in the SQL database, including the Locales themselves, but it would be ugly to put serialized Locale objects in it. I would rather store their String representations, which seem to be reasonably adequate.

+75
java locale
Mar 26 '10 at 9:47
source share
11 answers

See Locale.getLanguage() , Locale.getCountry() ... Save this combination in the database instead of "programatic name" ...
When you want to build 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); } 
+27
Mar 26 '10 at 9:57
source share
β€” -

A method that returns the locale from a string exists in the commons-lang library: LocaleUtils.toLocale(localeAsString)

+100
Jan 25 '11 at 12:20
source share

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

+45
Oct. 16 '12 at 10:13
source share

Java provides many things with the right implementation. Much can be avoided:

Examples:

  • This returns ms_MY .

     String key = ms-MY; Locale locale = new Locale.Builder().setLanguageTag(key).build(); 
  • This will return en_US

     String str = "en-US"; Locale locale = LocaleUtils.toLocale(str); System.out.println(locale.toString()); 
  • 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 LocaleUtils , and this Locale to learn additional methods.

+20
Jul 08 '15 at 10:49
source share

This answer may be a bit late, but it turns out that parsing a string is not as ugly as the OP suggested. I found this pretty 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 (in 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+ as per the documentation :

In particular, customers who analyze the toString output in the language, country, and variants can continue to do this (although this is very discouraged ), although the variant field will contain additional information in it if a script or extension is present.

Instead, use Locale.forLanguageTag and Locale.toLanguageTag, or, if necessary, Locale.Builder.

+12
Mar 06 '13 at 3:45
source share

An old question with a lot of answers, but here are more solutions:

+7
Dec 11 2018-10-11
source share

Option 1:

 org.apache.commons.lang3.LocaleUtils.toLocale("en_US") 

Option 2:

 Locale.forLanguageTag("en-US") 

Note: Option 1 is the underline between the language and the country, and Option 2 is the dash.

+5
May 16 '17 at 6:56 a.m.
source share

There is no static valueOf method for this, which is a bit surprising.

One rather ugly but easy way would be to Locale.getAvailableLocales() over Locale.getAvailableLocales() , comparing their toString values ​​with your value.

Not very nice, but no string parsing required. You can pre-fill the Map line from lines to locales and see your database line on this map.

+3
Mar 26 '10 at 9:51
source share

You can use this on Android. Works great for me.

 private static final Pattern localeMatcher = Pattern.compile ("^([^_]*)(_([^_]*)(_#(.*))?)?$"); public static Locale parseLocale(String value) { Matcher matcher = localeMatcher.matcher(value.replace('-', '_')); return matcher.find() ? TextUtils.isEmpty(matcher.group(5)) ? TextUtils.isEmpty(matcher.group(3)) ? TextUtils.isEmpty(matcher.group(1)) ? null : new Locale(matcher.group(1)) : new Locale(matcher.group(1), matcher.group(3)) : new Locale(matcher.group(1), matcher.group(3), matcher.group(5)) : null; } 
+2
Aug 25 '14 at 2:53
source share

Well, instead, I would save the string concatenation of Locale.getISO3Language() , getISO3Country() and getVariant (), which would allow me to call the Locale(String language, String country, String variant) constructor Locale(String language, String country, String variant) .

indeed, relying on displayLanguage implies using the language of the locale to display it, which makes it language dependent, contrary to the iso language code.

As an example, the en locale key will be saved as

 en_EN en_US 

etc.

+1
Mar 26 '10 at 10:00
source share

Because I just implemented it:

In Groovy / Grails this will be:

 def locale = Locale.getAvailableLocales().find { availableLocale -> return availableLocale.toString().equals(searchedLocale) } 
+1
Jul 10 2018-12-12T00:
source share



All Articles