How do I get a formatted date for a specific pattern and locale?

If you want to change formatting styles provided by DateFormat, you can uses SimpleDateFormat class. The SimpleDateFormat class is locale-sensitive.

If you instantiate SimpleDateFormat without a Locale parameter, it will format the date and time according to the default Locale. Both the pattern and the Locale determine the format. For the same pattern, SimpleDateFormat may format a date and time differently if the Locale varies.

package org.kodejava.example.text;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class SimpleDateFormatChangeLocalePattern {
    public static void main(String[] args) {
        String pattern = "dd-MMM-yyyy";
        Date today = new Date();

        //
        // Gets a formatted date according to the given pattern.
        // Here only the pattern is passed as argument of the
        // SimpleDateFormat constructor, so it will format the
        // date according to the default Locale.
        //
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String local = sdf.format(today);
        System.out.println("Date in default locale: " + local);

        Locale[] locales = {
                Locale.CANADA,
                Locale.FRANCE,
                Locale.GERMANY,
                Locale.US,
                Locale.JAPAN
        };

        for (Locale locale : locales) {
            //
            // Format a date according to the given pattern for each
            // locale.
            //
            sdf = new SimpleDateFormat(pattern, locale);
            String after = sdf.format(today);
            System.out.println(locale.getDisplayCountry() + 
                    " | format: " + after);
        }
    }
}

Here are the variety of output produces when formatting a date in the same date pattern but varies in Locale

Date in default locale: 10-Sep-2010
Canada			 | format: 10-Sep-2010
France			 | format: 10-sept.-2010
Germany			 | format: 10-Sep-2010
United States			 | format: 10-Sep-2010
Japan			 | format: 10-9-2010

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.