O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required