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: 12-Apr-2018
Canada | format: 12-Apr-2018
France | format: 12-avr.-2018
Germany | format: 12-Apr-2018
United States | format: 12-Apr-2018
Japan | format: 12-4-2018

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🙂.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.