Tutorial

Master Java Date Formatting: SimpleDateFormat & DateFormat Guide

Updated on October 25, 2022
Master Java Date Formatting: SimpleDateFormat & DateFormat Guide

Introduction

Java’s SimpleDateFormat and DateFormat classes are essential for handling date and time formatting in Java applications. These classes are part of the java.text package and provide a robust framework for converting dates to strings and vice versa, based on specific locales.

SimpleDateFormat allows you to define patterns for date and time formatting, making it highly customizable. For example, you can specify patterns like “dd-MM-yyyy” for dates or “HH:mm:ss” for times. This flexibility is crucial for applications that need to display dates and times in various formats depending on user preferences or regional settings.

DateFormat, on the other hand, provides a more straightforward approach to date and time formatting by using predefined styles such as SHORT, MEDIUM, LONG, and FULL. It also supports localization, ensuring that dates and times are formatted according to the conventions of different regions and languages.

However, it’s important to note that both SimpleDateFormat and DateFormat are not thread-safe. This means that if you are using these classes in a multi-threaded environment, you should create separate instances for each thread to avoid concurrency issues.

In recent years, Java has introduced the java.time package in Java 8, which offers a more modern and comprehensive approach to date and time handling. This package includes classes like LocalDate, LocalTime, LocalDateTime, and DateTimeFormatter, which provide better performance and thread safety. Despite this, SimpleDateFormat and DateFormat are still widely used, especially in legacy applications, making it essential to understand their usage and capabilities.

Java DateFormat

  • The DateFormat class is used to format dates into strings according to the locale specified. This is crucial for applications that need to present date and time information in a way that is familiar to users from different regions.
  • Locales are used to define the region and language, ensuring that date formats are culturally appropriate. For instance, the date 31st Dec 2017 is formatted as 31-12-2017 in India, whereas in the United States, it appears as 12-31-2017.
  • It’s important to note that DateFormat instances are not thread-safe. Therefore, it is advisable to create separate instances for each thread to avoid concurrency issues.

You can create a DateFormat object using the getDateInstance() and getTimeInstance() methods, which allow for flexible date and time formatting based on the desired locale.

Locale loc = new Locale("en", "US");
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, loc);

Note: The constructor Locale(String, String) is deprecated since version 19

Locale loc = new Locale.Builder().setLanguage("en").setRegion("US").build();

The getDateInstance method of DateFormat needs two input parameters. The first parameter specifies the DateFormat to use and the second parameter is the locale.

Using format

DateFormat class has a format method which is responsible for formatting.

Locale locale = new Locale("fr", "FR");
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
String date = dateFormat.format(new Date());
System.out.print(date);

This code will format the date in the French (fr) language and the France (FR) region:

Output
3 janv. 2018

Using getTimeInstance()

For creating a DateFormat instance we are using getDateInstance() method.

For performing a time format, we need an instance of time. We will be using getTimeInstance() method for getting an instance of time.

Locale locale = new Locale("fr", "FR");
DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
String date = dateFormat.format(new Date());
System.out.print(date);

This code will format the time in the French (fr) language and the France (FR) region:

Output
11:03:01

Java SimpleDateFormat

SimpleDateFormat is similar to DateFormat. The only major difference between them is that SimpleDateFormat can be used for formatting (Date to String conversion) and for parsing (String to Date conversion) with locale support, whereas DateFormat don’t have locale support. DateFormat is an abstract class that provides base support for date formatting and parsing. SimpleDateFormat is the concrete class that extends DateFormat class.

SimpleDateFormat can be created using the SimpleDateFormat constructor. The constructor is a parametrised constructor and needs a String pattern as the parameter.

String pattern = "MM-dd-yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

The String pattern is the pattern which will be used to format a date and the output will be generated in that pattern as “MM-dd-yyyy”.

Patterns

Let us have a look at the pattern syntax that should be used for the formatting pattern.

Letter for Pattern Date or Time component Examples
G Era designator AD
y Year 2018 (yyyy), 18 (yy)
M Month in year July (MMMM), Jul (MMM), 07 (MM)
w Results in week in year 16
W Results in week in month 3
D Gives the day count in the year 266
d Day of the month 09 (dd), 9(d)
F Day of the week in month 4
E Day name in the week Tuesday, Tue
u Day number of week where 1 represents Monday, 2 represents Tuesday and so on 2
a AM or PM marker AM
H Hour in the day (0-23) 12
k Hour in the day (1-24) 23
K Hour in am/pm for 12 hour format (0-11) 0
h Hour in am/pm for 12 hour format (1-12) 12
m Minute in the hour 59
s Second in the minute 35
S Millisecond in the minute 978
z Timezone Pacific Standard Time; PST; GMT-08:00
Z Timezone offset in hours (RFC pattern) -0800
X Timezone offset in ISO format -08; -0800; -08:00

Some letters should be used in different amount for different results like for month:

Type Pattern Example Output
Full Month MMMM July
Abbreviated Month MMM Jul
Numeric Month MM 07

Examples

Let us now look at some examples for different formats of date and time.

Pattern Result
MM/dd/yyyy 01/02/2018
dd-M-yyyy hh:mm:ss 02-1-2018 06:07:59
dd MMMM yyyy 02 January 2018
dd MMMM yyyy zzzz 02 January 2018 India Standard Time
E, dd MMM yyyy HH:mm:ss z Tue, 02 Jan 2018 18:07:59 IST

Using SimpleDateFormat()

In order to parse a date we need to create an instance of SimpleDateFormat using the constructor and then use the format() method:

String pattern = "MM-dd-yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date());
System.out.println(date);

This code will output “MM-dd-yyyy”:

Output
01-02-2018

This pattern produces “month in year”, “day in month”, and “year”. The type of character (and capitalization) and the amount of characters contribute to the string. The month would be represented as two digits, the day as two digits, and the year as four digits.

This code displayed the date of “January 2, 2018” as “01-02-2018”.

For parsing time, we have to change the pattern while creating SimpleDateFormat instance.

String pattern = "HH:mm:ss.SSSZ";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date());
System.out.println(date);

This code will output “HH:mm:ss.SSSZ”:

Output
13:03:15.454+0530

This pattern produces “hours”, “minutes”, “seconds”, “milliseconds”, and “timezone offset in hours (RFC pattern)”.

This code displayed the time as “13:03:15.454+0530”.

Using parse()

Parsing is the conversion of String into a java.util.Date instance. We can parse a string to a date instance using parse() method of the SimpleDateFormat class. For parsing a String to Date we need an instance of the SimpleDateFormat class and a string pattern as input for the constructor of the class.

String pattern = "MM-dd-yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date date = simpleDateFormat.parse("12-01-2018");
System.out.println(date);

This will output a date (12-01-2018) without a specified time:

Output
Sat Dec 01 00:00:00 IST 2018

Now let’s look at SimpleDateFormat example to parse time.

String pattern = "HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date date = simpleDateFormat.parse("22:00:03");
System.out.println(date);

This will output a time (22:00:03) without a specified date:

Output
Thu Jan 01 22:00:03 IST 1970

Because we have not specified any date the program considered epoch as the date (i.e., 01-Jan-1970).

Using Locale

We have worked with Locale as part of the DateFormat and we have seen that locales are used based on regions.

String pattern = "EEEEE MMMMM yyyy HH:mm:ss.SSSZ";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, new Locale("fr", "FR"));
Date date = simpleDateFormat.format(new Date());
System.out.println(date);

This code will format the current time in the French (fr) language and the France (FR) region:

Output
mardi janvier 2018 14:51:02.354+0530

The day and month are named in French based on the Locale provided as input - mardi is “Tuesday” and janvier is “January”.

Conclusion

In this article, you learned about Java’s SimpleDateFormat and DateFormat. For more advanced date and time handling in Java, consider using the java.time package introduced in Java 8, which includes LocalDate, LocalDateTime, and Instant. These classes provide a more comprehensive and flexible approach to date and time manipulation.

For a deeper understanding of these new classes, you can refer to the Java 8 Date, LocalDate, LocalDateTime, Instant tutorial, which explains how to work with the modern date-time API in Java.

If you need to convert Java dates into specific timezone formats, the tutorial How to Convert Java Date into Specific Timezone Format provides detailed guidance on handling time zones effectively.

Additionally, for those interested in understanding date and time concepts in JavaScript, the Understanding Date and Time in JavaScript tutorial offers insights into managing dates and times in JavaScript applications.

References:

FAQs

What is the format of date in Java SimpleDateFormat?

The SimpleDateFormat class in Java allows you to format and parse dates according to a specific pattern. Common patterns include:

  • yyyy: Year in 4 digits (e.g., 2024)
  • MM: Month in 2 digits (e.g., 01 for January)
  • dd: Day of the month in 2 digits (e.g., 09)
  • HH: Hour in 24-hour format (e.g., 14 for 2 PM)
  • mm: Minutes in 2 digits
  • ss: Seconds in 2 digits
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(new Date());

How to convert SimpleDateFormat to a date in Java?

To convert a SimpleDateFormat string to a Date object, use the parse() method:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "2024-12-19";
Date date = sdf.parse(dateString);

How do I create a date in yyyy-MM-dd format in Java?

To create a date in the yyyy-MM-dd format:

Use the SimpleDateFormat class to format a Date object.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(new Date());
System.out.println(formattedDate); // Output: 2024-12-19

What is the simple date format for DD MM YYYY in Java?

The format for DD MM YYYY in Java is “dd MM yyyy”. Here’s how to use it:

SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy");
String formattedDate = sdf.format(new Date());
System.out.println(formattedDate); // Output: 19 12 2024

How to convert date format from MM DD YYYY to DD MM YYYY in Java?

To convert a date from MM DD YYYY to DD MM YYYY, you need to parse the original format and reformat it into the desired format:

SimpleDateFormat inputFormat = new SimpleDateFormat("MM dd yyyy");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd MM yyyy");

String dateString = "12 19 2024";
Date date = inputFormat.parse(dateString);
String reformattedDate = outputFormat.format(date);

System.out.println(reformattedDate); // Output: 19 12 2024

How to get current date in Java in MM DD YYYY format?

To get the current date in MM DD YYYY format, use the SimpleDateFormat class:

SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy");
String currentDate = sdf.format(new Date());
System.out.println(currentDate); // Output: 12 19 2024

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author


Default avatar

Sr Technical Writer

Senior Technical Writer @ DigitalOcean | 2x Medium Top Writers | 2 Million+ monthly views & 34K Subscribers | Ex Cloud Consultant @ AMEX | Ex SRE(DevOps) @ NUTANIX


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
March 13, 2020

Wrong, “whereas DateFormat allows only formatting of Date.” it can be for parse string to Date

- sda

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 4, 2020

    This is the best tutorial on dates I have ever seen

    - Joe E

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      October 11, 2018

      You Should Append About Calendar Class because Date is deprecated

      - John Snow

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 24, 2018

        How can i set date format 20th may, 2010

        - sridhar

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          April 9, 2018

          Thank you for the article, it’s been very helpful. I believe the day of the week should be amended in this manner below: EEEE, E Day name in the week Tuesday(EEEE), Tue(E or EEE)

          - Shane McCurdy

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            January 4, 2018

            You Should have addressed the important topic like Date conversion to different TimeZones. Anyway great tutorial.

            - ManishS

              Try DigitalOcean for free

              Click below to sign up and get $200 of credit to try our products over 60 days!

              Sign up

              Join the Tech Talk
              Success! Thank you! Please check your email for further details.

              Please complete your information!

              Become a contributor for community

              Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

              DigitalOcean Documentation

              Full documentation for every DigitalOcean product.

              Resources for startups and SMBs

              The Wave has everything you need to know about building a business, from raising funding to marketing your product.

              Get our newsletter

              Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

              New accounts only. By submitting your email you agree to our Privacy Policy

              The developer cloud

              Scale up as you grow — whether you're running one virtual machine or ten thousand.

              Get started for free

              Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

              *This promotional offer applies to new accounts only.