Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use java.util.Locale to check for Australian locale

Tags:

java

locale

Question : How do I correctly use java.util.locale for checking a user's locale?

Summary : The legacy code I have uses a predefined static in Locale to check if a user is, for example, in France ...

if(Locale.FRANCE.equals(locale) || Locale.FRENCH.equals(locale)) {
    // do stuff
}

I wish to add some code to check if a user is in Australia. However, Locale only has a limited set of predefined statics, and AUSTRALIA is not one of them. I appear to be able to do the following ...

if(new Locale("AU").equals(locale)) {
    // do stuff
}

However, this is inconsistent with the existing code. What is the correct way of doing it? If the first example I have given is correct, why is the predefined list of statics so limited?

like image 570
Andy A Avatar asked Nov 08 '12 12:11

Andy A


People also ask

What is Java Util Locale?

The java.util.Locale class object represents a specific geographical, political, or cultural region. . Following are the important points about Locale − An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to form information for the user.

How do I find my Locale in Java?

To get equivalent information in Java, use Locale. getDefault() to get the Locale that Java is using, and use methods on the Locale object such as getCountry() , getLanguage() to get details. The information is available using ISO codes and as human readable/displayable names.


1 Answers

No. new Locale( "AU" ) would be the language "AU" (whatever that is). You need the two argument constructor!

The Locale.equals() methods compares both language, country and variant. You should probably check like this:

if ( "AU".equals( locale.getCountry() ) ) { /* do stuff */ }

As for why the list of predefined Locale's are so limited: Pass. We should probably be honored that there is anything but en_US at all :-)

Cheers,

like image 95
Anders R. Bystrup Avatar answered Oct 13 '22 00:10

Anders R. Bystrup