4

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

Dan Zhu
  • 49
  • 1
  • 6

1 Answers1

4

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

(read to the end)

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Maybe I didn't get it, but the OP says _I want to get country codes from a list of locale._ Here you are showing him how to get Locale from a country code, which is the exact opposite – BackSlash Jan 22 '14 at 20:16
  • @BackSlash As I understand it, if you only have the language tag, you need to retrieve the `Locale` to get its country. Or you can build up your own mapping. – Sotirios Delimanolis Jan 22 '14 at 20:17