Home  >  Article  >  Java  >  How to Get the Current Time with Millisecond Precision in YYYY-MM-DD HH:MM:Sec.Millisecond Format?

How to Get the Current Time with Millisecond Precision in YYYY-MM-DD HH:MM:Sec.Millisecond Format?

DDD
DDDOriginal
2024-11-17 09:00:04732browse

How to Get the Current Time with Millisecond Precision in YYYY-MM-DD HH:MM:Sec.Millisecond Format?

Obtaining the Current Time with Millisecond Precision in YYYY-MM-DD HH:MM:Sec.Millisecond Format

Original Question:

Precise retrieval of the current time in "YYYY-MM-DD HH:MM:Sec.Millisecond" format remains elusive. The provided code offers a valuable starting point, delivering the current time in "YYYY-MM-dd HH:mm:ss" format. However, it lacks the ability to capture milliseconds. How can this functionality be implemented using SimpleDateFormat?

Solution:

To retrieve milliseconds as part of the time format, we need to modify the SimpleDateFormat pattern slightly. The pattern "SSS" denotes milliseconds, so we can seamlessly incorporate it into our existing pattern:

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

Here's an updated example:

public static String getCurrentTimeStamp() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    Date now = new Date();
    String strDate = sdf.format(now);
    return strDate;
}

With this adjustment, you can now retrieve the current time in the desired "YYYY-MM-DD HH:MM:Sec.Millisecond" format.

The above is the detailed content of How to Get the Current Time with Millisecond Precision in YYYY-MM-DD HH:MM:Sec.Millisecond Format?. 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