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 use 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.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: 19-Oct-2021
Canada | format: 19-Oct.-2021
France | format: 19-oct.-2021
Germany | format: 19-Okt.-2021
United States | format: 19-Oct-2021
Japan | format: 19-10月-2021

How do I get default date and time format for a defined country?

The DateFormat class allows you to format dates and times with predefined styles in a locale-sensitive manner. Formatting dates or times with the DateFormat class is a two-step process.

First, you create a formatter with the getDateInstance() method for formatting date or getTimeInstance() method for formatting time or getDateTimeInstance() when you want formatting both date and time.

Second, you invoke the format method, which returns a String containing the formatted date. The following example formats today’s date and time by calling those two methods.

package org.kodejava.text;

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

public class LocaleDateTime {
    public static void main(String[] args) {
        Locale[] locales = {
                Locale.CANADA, Locale.FRANCE, Locale.GERMANY, Locale.US, 
                Locale.JAPAN
        };

        Date today = new Date();
        for (Locale locale : locales) {
            StringBuilder sb = new StringBuilder();
            sb.append(locale.getDisplayCountry()).append(System.lineSeparator());
            sb.append("------------------------").append(System.lineSeparator());

            // Gets a DateFormat instance for the specified locale
            // and format a date object by calling the format method.
            DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
            String date = df.format(today);
            sb.append("Default date format: ").append(date)
                    .append(System.lineSeparator());

            // Gets a DateFormat instance for the specified locale
            // and format a time information by calling the format method.
            DateFormat tf = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
            String time = tf.format(today.getTime());
            sb.append("Default time format: ").append(time)
                    .append(System.lineSeparator());

            System.out.println(sb);
        }

        // Gets date and time formatted value for Italy locale using
        // To display a date and time in the same String, create the
        // formatter with the getDateTimeInstance method.
        // The first parameter is the date style, and the second is
        // the time style. The third parameter is the Locale
        DateFormat dtf = DateFormat.getDateTimeInstance(DateFormat.DEFAULT,
                DateFormat.DEFAULT, Locale.ITALY);
        String datetime = dtf.format(today);

        System.out.println("date time format in " +
                Locale.ITALY.getDisplayCountry() + ": " + datetime);
    }
}

Here are the produces output:

Canada
------------------------
Default date format: Oct. 19, 2021
Default time format: 6:11:45 a.m.

France
------------------------
Default date format: 19 oct. 2021
Default time format: 06:11:45

Germany
------------------------
Default date format: 19.10.2021
Default time format: 06:11:45

United States
------------------------
Default date format: Oct 19, 2021
Default time format: 6:11:45 AM

Japan
------------------------
Default date format: 2021/10/19
Default time format: 6:11:45

date time format in Italy: 19 ott 2021, 06:11:45

How do I compare two dates?

In this example you’ll see the utilization of SimpleDateFormat class for comparing two dates for equality. We convert the date object into string using the DateFormat instance and then compare it using String.equals() method.

package org.kodejava.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class ComparingDate {
    public static void main(String[] args) {
        // Create a SimpleDateFormat instance with dd/MM/yyyy format
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

        // Get the current date
        Date today = new Date();

        // Create an instance of calendar that represents a new year date
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DATE, 1);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.YEAR, 2021);

        String newYear = df.format(calendar.getTime());
        String now = df.format(today);

        // Using the string equals method we can compare the date.
        if (now.equals(newYear)) {
            System.out.println("Happy New Year!");
        } else {
            System.out.println("Have a nice day!");
        }
    }
}

How do I check if a string is a valid date?

The following code can be used to validate if a string contains a valid date information. The pattern of the date is defined by the java.text.SimpleDateFormat object. When the date is not valid a java.text.ParseException will be thrown.

package org.kodejava.text;

import java.text.SimpleDateFormat;
import java.text.ParseException;

public class DateValidation {
    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

        // Input to be parsed should strictly follow the defined date format
        // above.
        format.setLenient(false);

        String date = "29/18/2021";
        try {
            format.parse(date);
        } catch (ParseException e) {
            System.out.println("Date " + date + " is not valid according to " +
                    format.toPattern() + " pattern.");
        }
    }
}

The result of the above date validation code is:

Date 29/18/2021 is not valid according to dd/MM/yyyy pattern.

How do I change date formatting symbols?

This example shows how we can change the date formatting symbols. In this example we change the month names and short month names and also the weekday names and short weekday names.

Other than these two items we can also change other symbols such as the Era name and AM-PM string.

package org.kodejava.text;

import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.util.Date;

public class DateFormatSymbolsExample {
    public static void main(String[] args) {
        // Defining a new Date Format Symbols, the following are month and day
        // names in Bahasa Indonesia.
        String[] newMonths = {"JANUARI", "FEBRUARI", "MARET", "APRIL", "MEI",
                "JUNI", "JULI", "AGUSTUS", "SEPTEMBER", "OKTOBER", "NOVEMBER",
                "DESEMBER"};
        String[] newShortMonths = {"JAN", "FEB", "MAR", "APR", "MEI", "JUN",
                "JUL", "AGU", "SEP", "OKT", "NOV", "DES"};
        String[] newWeekdays = {"", "MINGGU", "SENIN", "SELASA", "RABU", "KAMIS",
                "JUMAT", "SABTU"};
        String[] shortWeekdays = {"", "MIN", "SEN", "SEL", "RAB", "KAM", "JUM",
                "SAB"};

        DateFormatSymbols symbols = new DateFormatSymbols();
        symbols.setMonths(newMonths);
        symbols.setShortMonths(newShortMonths);
        symbols.setWeekdays(newWeekdays);
        symbols.setShortWeekdays(shortWeekdays);

        DateFormat format = new SimpleDateFormat("dd MMMM yyyy", symbols);
        System.out.println(format.format(new Date()));

        format = new SimpleDateFormat("dd MMM yyyy", symbols);
        System.out.println(format.format(new Date()));

        format = new SimpleDateFormat("EEEE, dd MMM yyyy", symbols);
        System.out.println(format.format(new Date()));

        format = new SimpleDateFormat("E, dd MMM yyyy", symbols);
        System.out.println(format.format(new Date()));
    }
}

The result of the code snippet above is:

02 OKTOBER 2021
02 OKT 2021
SABTU, 02 OKT 2021
SAB, 02 OKT 2021