Home > Java > javaTutorial > How do I include milliseconds when formatting the current time in Java?

How do I include milliseconds when formatting the current time in Java?

Barbara Streisand
Release: 2024-11-12 10:04:02
Original
764 people have browsed it

How do I include milliseconds when formatting the current time in Java?

Retrieving Current Time with Milliseconds in Java

To retrieve the current time in the format "YYYY-MM-DD HH:MM:SS.MS," where "MS" represents milliseconds, you can use the SimpleDateFormat class. However, the code you provided uses the SimpleDateFormat without specifying the millisecond format.

To include milliseconds, you need to modify the format string as follows:

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

Here's how this modified code works:

  1. Create an instance of SimpleDateFormat with the desired format string. This code specifies the pattern "yyyy-MM-dd HH:mm:ss.SSS," where "SSS" represents milliseconds.
  2. Use the format() method of the SimpleDateFormat instance to convert the current time (obtained using the Date object) to a formatted string.

With this modification, the code will return the current time in the desired format: YYYY-MM-DD HH:MM:SS.MS. For example, if the current time is 2023-03-08 14:35:23 and the milliseconds are 125, the output will be "2023-03-08 14:35:23.125."

The above is the detailed content of How do I include milliseconds when formatting the current time in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template