Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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));
    }
}
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata