How to convert String to locale in java

I need to convert the given string to a locale. The string has the value "fr_US" and I need to convert it to a locale (in java.util.locale).

I found one method in "org.apache.commons.lang.LocaleUtils" that does the conversion, but I'm looking for a way that will convert to "java.util.locale"

String val = "fr_US";
locale l1 = LocaleUtils.toLocale(val);
// this converts into org.apache.commons.lang.LocaleUtils
+4
source share
2 answers

You can do:

String val = "fr_US";
String[] tab = val.split("_");
Locale locale = new Locale(tab[0], tab[1]);

Or if you hard coded val

Locale locale = new Locale("fr", "US");

We also Localehave a method forLanguageTag, but as a parameter you must pass the BCP 47 language tag (s -, not _).

+3
source

apache, :

Locale myLocale =  LocaleUtils.toLocale("fr_US");

Locale myLocale = new Locale("fr", "US");
0

Source: https://habr.com/ru/post/1679591/


All Articles