W3docs

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

To get the current time in the YYYY-MM-DD HH:MI:Sec.Millisecond format in Java, you can use the SimpleDateFormat class and specify the desired format string:

To get the current time in the YYYY-MM-DD HH:MI:Sec.Millisecond format in Java, you can use the SimpleDateFormat class and specify the desired format string. (Note: The title notation is informal; Java's pattern uses mm for minutes, ss for seconds, and SSS for milliseconds.)


import java.text.SimpleDateFormat;
import java.util.Date;

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String currentTime = sdf.format(new Date());

This creates a SimpleDateFormat object with the format string, then uses the format method to convert the current time (as a Date object) into a string. The resulting string matches the requested format.

Here is a breakdown of the format string:

  • yyyy: The four-digit year
  • MM: The month as a two-digit number (01-12)
  • dd: The day of the month as a two-digit number (01-31)
  • HH: The hour as a two-digit number in 24-hour format (00-23)
  • mm: The minute as a two-digit number (00-59)
  • ss: The second as a two-digit number (00-59)
  • SSS: The milliseconds as a three-digit number (000-999)

Important notes:

  • SimpleDateFormat is not thread-safe. Create a new instance per thread or use ThreadLocal if sharing across threads.
  • For Java 8+, the java.time API is recommended over these legacy classes:
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
    String currentTime = LocalDateTime.now().format(formatter);

I hope this helps! Let me know if you have any other questions.