java.time
The accepted answer uses the legacy API (java.util Date-Time API and their formatting API, SimpleDateFormat) which was the right thing to do at the time of writing that answer. However, Java-8 brought the modern Date-Time API which supplanted the outdated and error-prone legacy date-time API and their formatting API. Since then it has been highly recommended to switch to the modern API.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Note that java.time types are thread-safe.
Solution using java.time, the modern Date-Time API: Format LocalDateTime#now with a DateTimeFormatter using the required format.
LocalDateTime.now()
.format(
DateTimeFormatter.ofPattern(
"MM/dd/uuuu hh:mm:ss a", Locale.ENGLISH));
Notes:
- Here, you can use
y instead of u but I prefer u to y.
- Always specify a
Locale with a SimpleDateFormat, and a DateTimeFormatter for custom formats.. Note that Predefined Formatters do not accept Locale (i.e. they work with the system's Locale).
Demo:
public class Main {
public static void main(String[] args) {
// Get the current date-time in your system's time-zone
// Note: if you want to get the current date-time in a specific time-zone,
// use LocalDateTime.now(ZoneId)
LocalDateTime now = LocalDateTime.now();
// Default format
System.out.println(now);
// Custom format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/uuuu hh:mm:ss a", Locale.ENGLISH);
String dtInCustomFormat = now.format(formatter);
System.out.println(dtInCustomFormat);
}
}
Output from a sample run:
2023-11-13T20:54:51.573121
11/13/2023 08:54:51 PM
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.