How to Get Current DateTime in Java with Format (yyyy-MM-dd HH:mm:ss.SSS)
How can we obtain the current datetime in Java, following this format: yyyy-MM-dd HH:mm:ss.SSS?
1. Using Java 8’s LocalDateTime
We can use LocalDateTime.now() and a DateTimeFormatter to obtain the current datetime string with a custom format.
String getCurrentDateTime() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
return LocalDateTime.now().format(dtf);
}
2. Using Instant
We can do the same with Instant.now() with some string replacements.
String getCurrentDateTime() {
String instant = Instant.now().toString(); // 2022-07-04T12:12:12.121Z
return instant.replace("T", " ").replace("Z", "");
}
3. Using SimpleDateFormat
Prior to Java 8, using SimpleDateFormat with new Date() was a great, simple option.
String getCurrentDateTime() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
}
Keep in mind that
SimpleDateFormatis not thread-safe.