Using a Particular Locale

Problem

You want to use a locale other than the default in a particular operation.

Solution

Use Locale.getInstance(Locale) .

Discussion

Classes that provide formatting services, such as DateFormat and NumberFormat, provide an overloaded getInstance( ) method that can be called either with no arguments or with a Locale argument.

To use these, you can use one of the predefined locale variables provided by the Locale class, or you can construct your own Locale object giving a language code and a country code:

Locale locale1 = Locale.FRANCE;    // predefined
Locale locale2 = new Locale("en", "UK");    // English, UK version

Either of these can be used to format a date or a number, as shown in class UseLocales :

import java.text.*; import java.util.*; /** Use some locales * choices or -Duser.lang= or -Duser.region=. */ public class UseLocales { public static void main(String[] args) { Locale frLocale = Locale.FRANCE; // predefined Locale ukLocale = new Locale("en", "UK"); // English, UK version DateFormat defaultDateFormatter = DateFormat.getDateInstance( DateFormat.MEDIUM); DateFormat frDateFormatter = DateFormat.getDateInstance( DateFormat.MEDIUM, frLocale); DateFormat ukDateFormatter = DateFormat.getDateInstance( DateFormat.MEDIUM, ukLocale); Date now = new Date( ); System.out.println("Default: " + ' ' + defaultDateFormatter.format(now)); System.out.println(frLocale.getDisplayName( ) + ' ' + frDateFormatter.format(now)); System.out.println(ukLocale.getDisplayName( ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.