Home  >  Article  >  Java  >  How to Format the Current Time in Java with Millisecond Precision?

How to Format the Current Time in Java with Millisecond Precision?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-12 03:02:011016browse

How to Format the Current Time in Java with Millisecond Precision?

Obtaining Current Time with Millisecond Precision in Java

In Java, the SimpleDateFormat class can be utilized to format dates and times. However, by default, it does not include milliseconds in its formatting. Here's how to obtain the current time in "YYYY-MM-DD HH:MI:Sec.Millisecond" format:

To include milliseconds in the formatted time string, the following code can be used:

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

This code creates a SimpleDateFormat object with the desired time format. The .SSS at the end of the format string specifies that milliseconds should be included in the output.

Here's an example of how to use the modified code:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
System.out.println(strDate);

Output:

2023-03-08 15:47:08.128

Now, the formatted current time includes milliseconds, providing the desired precision.

The above is the detailed content of How to Format the Current Time in Java with Millisecond Precision?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn