Format Date to yyyy-MM-dd in java

In this post, we will see how to Format Date to yyyy-MM-dd in java.

There are multiple ways to format Date to yyyy-MM-dd in java. Let’s go through them.

Using DateTimeFormatter with LocalDate (Java 8)

To Format Date to yyyy-MM-dd in java:

  • Create a LocalDateTime object.
  • Use DateTimeFormatter.ofPattern() to specify the pattern yyyy-MM-dd
  • Call format() method on DateTimeFormatter and pass LocalDateTime object
  • Get result in String with date format yyyy-mm-dd.

Let’s see with the help of example:

Output:

Formatted Date in String format: 2022-05-25

Using SimpleDateFormat

To Format Date to yyyy-MM-dd in java:

  • Create Date object
  • Create SimpleDateFormat with pattern yyyy-MM-dd
  • Call format() method on SimpleDateFormat and pass Date object
  • Get result in String with date format yyyy-mm-dd.

Output:

Original Date: Wed May 25 11:41:27 IST 2022
Formatted Date in String format: 2022-05-25

Using Calendar class

To Format Date to yyyy-MM-dd in java:

  • Use Calendar's setTime() method to set current date
  • Use calendar class to get day, month and year using Calendar.get() methods.
  • Create format yyyy-MM-dd using String concatenation.

This is not a recommended approach as it does not specify format explicitly and is more error prone.

Let’s see with the help of example:

Output:

Formatted Date in yyyy-MM-dd format: 2022-05-25

Note that we have added 1 after getting month using calendar.get(Calendar.MONTH) because it returns month from 0 to 11. 0 denotes January and 11 denotes December.

That’s all about how to Format Date to yyyy-MM-dd in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *