Constants
Locale
class provides a number of constants for frequently used locales: Locale.CANADA
, Locale.CANADA_FRENCH
, Locale.CHINA
, Locale.UK
, etc.
Instead of creating a new instance of locale for English as a language and US as a country via new Locale("en", "US")
it's preferable to use static field Locale.US
.
Locale constructors
There are three overloaded constructors which allow you to create a Local
object from language, country and variant.
If you're enough with this information, go with a constructor.
Note: constructor call always creates a new object in memory.
Locale.forLanguageTag
Static method Locale#forLanguageTag()
allows to construct an instance of Locale
by providing IETF BCP 47 language tag (also see RFC 4647 "Matching of Language Tags" and RFC 5646 "Tags for Identifying Languages").
Withing a language tag apart from the language and country you can specify various details like calendar, numeric system, currency.
Note: forLanguageTag()
(as well as Local.Builder
) after parsing is complete, provides an instance from the Cache (if already exists).
Example:
Locale buddhistCal = Locale.forLanguageTag("en-EN-u-ca-buddhist");
Locale arabicNum = Locale.forLanguageTag("en-EN-u-nu-arab");
Locale thaiNum = Locale.forLanguageTag("en-EN-u-nu-thai");
LocalDate date = LocalDate.now();
System.out.println(date);
System.out.println(date.format(DateTimeFormatter.ISO_DATE.localizedBy(buddhistCal)));
System.out.println(date.format(DateTimeFormatter.ISO_DATE.localizedBy(arabicNum)));
System.out.println(date.format(DateTimeFormatter.ISO_DATE.localizedBy(thaiNum)));
Output:
2022-09-07
2565-09-07 // buddhist calendar
٢٠٢٢-٠٩-٠٧ // arabic numbers
๒๐๒๒-๐๙-๐๗ // thai numbers
Locale.US
would be best. Are the parameters you pass into it variable and you therefor cannot use the existing defined static variable? – Lorylosenew
). This is not to say you won't get a new instance with the factory method, just that you don't have to. But, if there is a static member, as mentioned by @OHGODSPIDERS, that's even better again. – LubricousforLanguageTag()
gives stricter argument validation? If so, use it, validation is invaluable. – UnderdrawersforLanguageTag()
do its thing. – Justifynew Locale()
is DEPRECATED – Covington