Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String into locale in java

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

I found one method in "org.apache.commons.lang.LocaleUtils" that does the conversion but I am looking for a method that converts into "java.util.locale"

String val = "fr_US";
locale l1 = LocaleUtils.toLocale(val);
// this converts into org.apache.commons.lang.LocaleUtils
like image 412
pjain Avatar asked Jun 19 '17 07:06

pjain


People also ask

What is Java locale string?

The Java Locale class object represents a specific geographic, cultural, or political region. It is a mechanism to for identifying objects, not a container for the objects themselves. A Locale object logically consists of the fields like languages, script, country, variant, extensions.

What is locale in Java with example?

A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user.

How do I get language code from locale?

Use of Locale Use getCountry to get the country (or region) code and getLanguage to get the language code. You can use getDisplayCountry to get the name of the country suitable for displaying to the user. Similarly, you can use getDisplayLanguage to get the name of the language suitable for displaying to the user.


1 Answers

You can do:

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

Or, if you hardcoded you val

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

Also in Locale we have a method forLanguageTag but as parameter you have to pass BCP 47 language tag (with -, not _).

like image 53
ByeBye Avatar answered Sep 28 '22 05:09

ByeBye