Setting the Default Locale
Problem
You want to
change the default
Locale
for all operations within a given Java
runtime.
Solution
Set the
system property
user.language
, or call Locale.setDefault( )
.
Discussion
Here is a program called SetLocale
, which takes
the language and country codes from the command line, constructs a
Locale
object, and passes it to
Locale.setDefault( )
. When run with different
arguments, it prints the date and a number in the appropriate locale:
C:\javasrc\i18n>java SetLocale en US 6/30/00 1:45 AM 123.457 C:\javasrc\i18n>java SetLocale fr FR 30/06/00 01:45 123,457
The code is similar to the previous recipe in how it constructs the locale.
import java.text.*; import java.util.*; /** Change the default locale */ public class SetLocale { public static void main(String[] args) { switch (args.length) { case 0: Locale.setDefault(Locale.FRANCE); break; case 1: throw new IllegalArgumentException( ); case 2: Locale.setDefault(new Locale(args[0], args[1])); break; default: System.out.println("Usage: SetLocale [language [country]]"); // FALLTHROUGH } DateFormat df = DateFormat.getInstance( ); NumberFormat nf = NumberFormat.getInstance( ); System.out.println(df.format(new Date( ))); System.out.println(nf.format(123.4567)); } }
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.