cupakob
cupakob

Reputation: 8531

How to get iso2 language code for locale?

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.

Upvotes: 13

Views: 24188

Answers (5)

saint
saint

Reputation: 64

What about using the toLanguageTag() method?

Example:

public String getLang(Locale language) {
    return language.toLanguageTag();
}

Upvotes: 1

Brod
Brod

Reputation: 1465

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];
}

Upvotes: 9

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74760

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.

Upvotes: 14

Thomas
Thomas

Reputation: 88707

Locale locale = ?; locale.getLanguage();

Upvotes: 1

Riduidel
Riduidel

Reputation: 22292

Maybe by calling Locale#getLanguage()

Upvotes: 1

Related Questions