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

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));
    }
}

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