Recipe 15.8 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( ) + ' ' +             ukDateFormatter.format(now));     } }

The program prints the locale name and formats the date in each of the locales:

$ java UseLocales Default:  Nov 30, 2000 French (France) 30 nov. 00 English (UK) Nov 30, 2000 $



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net