java.time
The accepted answer is correct and also applicable to the modern date-time API. More in the documentation.
Note that Java-8, released in March 2014, introduced the modern date-time API which supplanted the outdated and error-prone java.util
Date-Time API and their formatting API, SimpleDateFormat
. Since then it has been strongly recommended to switch to the modern Date-Time API.
Demo using java.time
, the modern Date-Time API:
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ENGLISH);
System.out.println(LocalDate.now().format(formatter));
// Alternatively,
System.out.println(formatter.format(LocalDate.now()));
}
}
Output:
19/07/2023
19/07/2023
ONLINE DEMO
Note: Here, you can use y
instead of u
but I prefer u
to y
.
Learn more about the modern Date-Time API from Trail: Date Time.