This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

How do I obtain the current time in YYYY-MM-DD HH: MI: ms format in Java?

The code below gives me the current time. But that doesn’t account for milliseconds.

public static String getCurrentTimeStamp() { SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //dd/MM/yyyy Date now = new Date(); String strDate = sdfDate.format(now); return strDate; }Copy the code

I have a date in format YYYY-MM-DD HH:MM:SS (2009-09-22 16:47:08).

But I want to retrieve the current time in YYYY-MM-DD HH:MM: ss.ms (2009-09-22 16:47:08.128 milliseconds) format.

SimpleTextFormat will work fine. Here, the minimum unit of time is seconds, but how do you get milliseconds?

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}

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

Answer:

Java a line

public String getCurrentTimeStamp() {
    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
}
Copy the code

In the style of JDK8

public String getCurrentLocalDateTimeStamp() {
    return LocalDateTime.now()
       .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
}

Copy the code

The article translated from kgs4h5t57thfb6iyuz6dqtun5y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 1…

Note that SimpleDateFormat is not thread-safe in high-concurrency scenarios. It is static and can be used to solve the problem by using ThreadLocal. The current thread holds an object. You can also use DateTimeFormatter to make this thread safe.Java string to date conversion?


Welcome to my column S t a c k O v e r F l o w . I select the best questions and answers and test them frequently in interviews ! ! !   \color{red} Welcome to my column StackOverFlow, I will filter the quality of the interview test!! {~}


There are the latest and elegant ways to do this, and I will write my thoughts on this q&A at the end of the article \color{red} has the latest, elegant implementation, and I will also write my opinion on this question at the end of the article {~}

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️