How do I get pattern string of a SimpleDateFormat?

To format a java.util.Date object we use the SimpleDateFormat class. To get back the string pattern that were used to format the date we can use the toPattern() method of this class.

package org.kodejava.text;

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

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

        // Gets a pattern string describing this date format used by the
        // SimpleDateFormat object.
        String pattern = format.toPattern();

        System.out.println("Pattern = " + pattern);
        System.out.println("Date    = " + format.format(new Date()));
    }
}

The result of the program will be as follow:

Pattern = EEEE, dd/MM/yyyy
Date    = Tuesday, 26/10/2021

How do I change the date format symbols for a specified locale?

package org.kodejava.text;

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

public class ChangeDateFormatSymbols {
    public static void main(String[] args) {
        Locale id = new Locale("in", "ID");
        String pattern = "EEEE, dd MMM yyyy";
        Date today = new Date();

        // Gets formatted date specify by the given pattern for
        // Indonesian Locale no changes for default date format
        // is applied here.
        SimpleDateFormat sdf = new SimpleDateFormat(pattern, id);
        String before = sdf.format(today);
        System.out.println("Before format change: " + before);

        // Create a DateFormatSymbols object for Indonesian locale.
        DateFormatSymbols dfs = new DateFormatSymbols(id);

        // Gets String array of default format of weekdays.
        String[] days = dfs.getWeekdays();
        String[] newDays = new String[days.length];
        for (int i = 0; i < days.length; i++) {
            // For each day, apply toUpperCase() method to
            // capitalized it.
            newDays[i] = days[i].toUpperCase();
        }

        // Set String array of weekdays.
        dfs.setWeekdays(newDays);

        // Gets String array of default format of short months.
        String[] shortMonths = dfs.getShortMonths();
        String[] months = new String[shortMonths.length];
        for (int j = 0; j < shortMonths.length; j++) {
            // For each short month, apply toUpperCase() method
            // to capitalized it.
            months[j] = shortMonths[j].toUpperCase();
        }

        // Set String array of short months.
        dfs.setShortMonths(months);

        // Create a SimpleDateFormat object by given pattern and 
        // symbol and then format the date object as String.
        sdf = new SimpleDateFormat(pattern, dfs);
        String after = sdf.format(today);
        System.out.println("After change format : " + after);
    }
}

Here are the output of our program:

Before format change: Selasa, 19 Okt 2021
After change format : SELASA, 19 OKT 2021

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 format date using a locale based format?

The code below demonstrate how to format date information for a specific locale. In the example utilize the java.text.SimpleDateFormat class.

package org.kodejava.text;

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

public class FormatDateLocale {
    public static void main(String[] args) {
        // Defines an array of Locale we are going to use for
        // formatting date information.
        Locale[] locales = new Locale[] {
            Locale.JAPAN,
            Locale.CHINA,
            Locale.KOREA,
            Locale.TAIWAN,
            Locale.ITALY,
            Locale.FRANCE,
            Locale.GERMAN
        };

        // Get an instance of current date time
        Date today = new Date();

        // Iterates the entire Locale defined above and create a long
        // formatted date using the SimpleDateFormat.getDateInstance()
        // with the format, the Locale and the date information.
        for (Locale locale : locales) {
            System.out.printf("Date format in %s = %s%n",
                locale.getDisplayName(), SimpleDateFormat.getDateInstance(
                    SimpleDateFormat.LONG, locale).format(today));
        }
    }
}

The result of our code are:

Date format in Japanese (Japan) = 2021年10月6日
Date format in Chinese (China) = 2021年10月6日
Date format in Korean (South Korea) = 2021년 10월 6일
Date format in Chinese (Taiwan) = 2021年10月6日
Date format in Italian (Italy) = 6 ottobre 2021
Date format in French (France) = 6 octobre 2021
Date format in German = 6. Oktober 2021

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

How do I convert milliseconds value to date?

package org.kodejava.util;

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

public class MillisecondsToDate {
    public static void main(String[] args) {
        // Create a DateFormatter object for displaying date information.
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");

        // Get date and time information in milliseconds
        long now = System.currentTimeMillis();

        // Create a calendar object that will convert the date and time value
        // in milliseconds to date. We use the setTimeInMillis() method of the
        // Calendar object.
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(now);

        System.out.println(now + " = " + formatter.format(calendar.getTime()));
    }
}

The output of the code snippet above is:

1632868662762 = 29/09/2021 06:37:42.762

How do I set default Locale?

package org.kodejava.util;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

public class DefaultLocaleExample {
    public static void main(String[] args) {
        // Use Random class to generate some random number
        Random random = new Random();

        // We use the system default locale to format a number and a date.
        NumberFormat formatter = new DecimalFormat();
        Locale locale = Locale.getDefault();
        System.out.println("Default Locale = " + locale);
        System.out.println("Number         = " + formatter.format(random.nextDouble()));
        System.out.println("Date           = " + new SimpleDateFormat().format(new Date()));

        // We change the default locale to Locale.ITALY by setting it through 
        // the Locale.setDefault() method, and then we format another number
        // and date using a new locale. This change will affect all the class 
        // that aware to the Locale, such as the NumberFormat class.
        Locale.setDefault(Locale.ITALY);
        NumberFormat newFormatter = new DecimalFormat();
        System.out.println("New Locale     = " + Locale.getDefault());
        System.out.println("Number         = " + newFormatter.format(random.nextDouble()));
        System.out.println("Date           = " + new SimpleDateFormat().format(new Date()));
    }
}

The result of the code snippet above are:

Default Locale = en_US
Number         = 0.557
Date           = 9/26/21, 12:05 PM
New Locale     = it_IT
Number         = 0,217
Date           = 26/09/21, 12:05

How do I convert string date to long value?

package org.kodejava.util;

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

public class StringDateToLong {
    public static void main(String[] args) {
        // Here we have a string date, and we want to covert it to long value
        String today = "25/09/2021";

        // Create a SimpleDateFormat which will be used to convert the string to
        // a date object.
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        try {
            // The SimpleDateFormat parse the string and return a date object.
            // To get the date in long value just call the getTime method of
            // the Date object.
            Date date = formatter.parse(today);
            long dateInLong = date.getTime();

            System.out.println("Date         = " + date);
            System.out.println("Date in Long = " + dateInLong);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

The result of the code snippet:

Date         = Sat Sep 25 00:00:00 CST 2021
Date in Long = 1632499200000