Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get country code from locale?

Tags:

java

locale

I want to get country codes from a list of locale. e.g. I have inputs: en_US, dua_CM, zh-Hans_MO ... I want to output corresponding country code: US, CM, MO... (I am not sure if country code is the last two characters of locale...)

I tried the following Java code, but it printed out null.

    Locale lc = new Locale("en_US");
    System.out.print(lc.getCountry());

Any suggestions? Thanks in advance!

Dan

like image 394
Dan Zhu Avatar asked Sep 06 '25 03:09

Dan Zhu


1 Answers

Here, you are defining your own Locale, for which you haven't specified a Country value (see the overloaded Locale constructors).

Instead, use

Locale lc = Locale.forLanguageTag("en-US"); // Java 1.7

which will get the Locale object from Java's supported locales.


Also, related

  • en_US or en-US, which one should you use?

(read to the end)

like image 72
Sotirios Delimanolis Avatar answered Sep 07 '25 21:09

Sotirios Delimanolis