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 be parsing the String and then constructing a new Locale instance according to that, but maybe there's a better way / ready solution for that?
The need is that I want to store some locale specific settings in a SQL database, including Locales themselves, but it would be ugly to put serialized Locale objects there. I would rather store their String representations, which seem to be quite adequate in detail.
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:
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:
Use Locale.forLanguageTag and Locale.toLanguageTag instead, or if you must, Locale.Builder.
There doesn't seem to be a static
valueOf
method for this, which is a bit surprising.One rather ugly, but simple, way, would be to iterate over
Locale.getAvailableLocales()
, comparing theirtoString
values with your value.Not very nice, but no string parsing required. You could pre-populate a
Map
of Strings to Locales, and look up your database string in that Map.Well, I would store instead a string concatenation of
Locale.getISO3Language()
,getISO3Country()
and getVariant() as key, which would allow me to latter callLocale(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
and so on ...
Old question with plenty of answers, but here's more solutions:
Java provides lot of things with proper implementation lot of complexity can be avoided. This returns ms_MY.
Apache Commons has
LocaleUtils
to help parse a string representation. This will return en_USYou can also use locale constructors.
Please check this LocaleUtils and this Locale to explore more methods.
If you are using Spring framework in your project you can also use:
Documentation: