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.
[toc]
Using DateTimeFormatter with LocalDate (Java 8)
To Format Date to yyyy-MM-dd in java:
- Create a
LocalDateTimeobject. - Use
DateTimeFormatter.ofPattern()to specify the patternyyyy-MM-dd - Call
format()method onDateTimeFormatterand passLocalDateTimeobject - Get result in String with date format
yyyy-mm-dd.
Let’s see with the help of example:
package org.arpit.java2blog;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class FormatLocalDate {
public static void main(String[] args) {
LocalDateTime ldt = LocalDateTime.now();
String formattedDateStr = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH)
.format(ldt);
System.out.println("Formatted Date in String format: "+formattedDateStr);
}
}
Output:
Using SimpleDateFormat
To Format Date to yyyy-MM-dd in java:
- Create Date object
- Create
SimpleDateFormatwith patternyyyy-MM-dd - Call
format()method onSimpleDateFormatand passDateobject - Get result in String with date format yyyy-mm-dd.
package org.arpit.java2blog;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FormatUsingSimpleDateFormat {
public static void main(String[] args) {
Date date = new Date();
System.out.println("Original Date: "+date);
// Specify format as "yyyy-MM-dd"
SimpleDateFormat dmyFormat = new SimpleDateFormat("yyyy-MM-dd");
// Use format method on SimpleDateFormat
String formattedDateStr = dmyFormat.format(date);
System.out.println("Formatted Date in String format: "+formattedDateStr);
}
}
Output:
Formatted Date in String format: 2022-05-25
Further reading:
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:
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class FormatWithCalendar {
public static void main(String[] args) {
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH) + 1; // {0 - 11}
int year = calendar .get(Calendar.YEAR);
String yyyymmddFormat = (year)+"-"+((month<10)?"0"+month:month) + "-" + ((day<10)?"0"+day:day);
System.out.println("Formatted Date in yyyy-MM-dd format: " + yyyymmddFormat);
}
}
Output:
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.