Explain Codes LogoExplain Codes Logo

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

java
date-time
java-8
best-practices
Alex KataevbyAlex Kataev·Feb 18, 2025
TLDR

In Java, snag the current time including milliseconds with this piece of code:

import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")); System.out.println(currentTime); // And boom! You've got milliseconds!

Understanding the Concepts

Working with Time Zones

When universal time is your jam, use ZonedDateTime to specify a time zone for your current time:

import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.ZoneId; String currentTime = ZonedDateTime.now(ZoneId.of("UTC")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")); System.out.println(currentTime); // Who said timezone handling has to be hard?

For the Legacy Code Aficionados

Stuck in a pre-Java 8 world? SimpleDateFormat comes to your rescue:

import java.text.SimpleDateFormat; import java.util.Date; String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()); System.out.println(currentTime); // Putting the "fun" back in "function!"

Just remember, it's not thread-safe. So keep it locked down when multiple threads are involved!

When Instant becomes eternity

The Instant class represents a moment on the timeline. Format this bad boy like this:

import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.ZoneId; String currentTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS") .withZone(ZoneId.systemDefault()) .format(Instant.now()); System.out.println(currentTime); // Instant just got an upgrade!

Don't sweat the small stuff! Instant truncates to the nearest millisecond during formatting.

Embrace the Future with Java 8 (and Beyond)

Java 8's java.time eases date-time operations with immutable and thread-safe classes like DateTimeFormatter and LocalDateTime. Like regular shampoo and conditioner - in one bottle!

Tailoring your Time Display

Jazz up your time representation by using DateTimeFormatter.ISO_LOCAL_DATE_TIME:

import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; LocalDateTime now = LocalDateTime.now(); String isoDateTime = now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME).replace("T", " "); System.out.println(isoDateTime); // Finally got that "T" out of the way!

Pitfalls in formatting time

When handling date and time around the globe, locale-sensitive data isn't something to ignore. Specify your Locale when creating your DateTimeFormatter:

import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.US); // Stars, Stripes, and Lots of Dates!