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.
andy Mar 06 '13 at 3:45 2013-03-06 03:45
source share