Java – Get Current Date in YYYY-MM-DD Format
To get current date in YYYY-MM-DD format in Java, where YYYY-MM-DD is Year-Month-Day
- Import LocalDate class from java.time package.
- Create LocalDate object by calling static method now() of LocalDate class. LocalDate.now() method returns the current date from the system clock in the default time zone.
- Create DateTimeFormatter from DateTimeFormatter.ofPattern() method and pass the pattern
"yyyy-MM-dd"
as argument to ofPattern() method. - Call format() method on this LocalDate object with DateTimeFormatter object passed as argument. The format() method returns a string with the date formatted in the given pattern
"yyyy-MM-dd"
.
Example
In the following program, we shall use LocalDate and DateTime classes to format date in the pattern "yyyy-MM-dd"
.
Java Program
</>
Copy
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Example {
public static void main(String[] args) {
LocalDate dateObj = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String date = dateObj.format(formatter);
System.out.println(date);
}
}
Output
2021-02-18
format() method returned the date in the specified pattern.
Conclusion
In this Java Tutorial, we learned how to get current date in YYYY-MM-DD format using LocalDate and DateTimeFormatter classes of java.time package, with example program.