13

I'm getting the iso2 language code this way:

public String getLang(Locale language)
    return language.toString().substring(0,2).toLowerCase()
}

Is there better way to do this?

edit: when i use getLanguage, i get an empty string.

cupakob
  • 8,411
  • 24
  • 67
  • 76

5 Answers5

14

What about

public String getLang(Locale language)
    return language.getLanguage();
}

Of course, this will only be a iso 639-1 2-lettercode if there is one defined for this language, otherwise it may return a 3-letter code (or even longer).


Your code will give silly results if you have a locale without language code (like _DE) (mine will then return the empty string, which is a bit better, IMHO). If the locale contains a language code, it will return it, but then you don't need the toLowerCase() call.

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
  • For me this returns "nl_be", instead of the expected "nl". How is this possible? I had to use locale.getLanguage().split("_")[0] to get it :( – Wouter Apr 23 '14 at 07:36
  • This does not work. Need to split the string. At least with Java 8 – emirc Nov 30 '18 at 19:22
9

I had the same questions and this is what I found.

If you create the Locale with the constructor as:

Locale locale = new Locale("en_US");

and then you call getLanguage:

String language = locale.getLanguage();

The value of language will be "en_us";

If you create the Locale with the builder:

Locale locale = new Locale.Builder().setLanguage("en").setRegion("US").build()

Then the value locale.getLanguage() will return "en".

This is strange to me but it's the way it was implemented.

So this was the long answer to explain that if you want the language code to return a two-letter ISO language you need to use the Java Locale builder or do some string manipulation.

Your method with substring works but I would use something like I wrote below to cover instances where the delimiter may be "-" or "_".

public String getLang(Locale language)
    String[] localeStrings = (language.split("[-_]+"));
    return localeStrings[0];
}
Brod
  • 1,377
  • 12
  • 14
  • The issue here is that the constructor you are using is not parsing the code, but setting it as the "language" value. See https://stackoverflow.com/questions/2522248/how-to-get-locale-from-its-string-representation-in-java for how to parse it. – Paŭlo Ebermann Jun 29 '23 at 19:24
1

Maybe by calling Locale#getLanguage()

Riduidel
  • 22,052
  • 14
  • 85
  • 185
1

Locale locale = ?; locale.getLanguage();

Thomas
  • 87,414
  • 12
  • 119
  • 157
1

What about using the toLanguageTag() method?

Example:

public String getLang(Locale language) {
    return language.toLanguageTag();
}
J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94
saint
  • 54
  • 4