"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Java timestamps to formatted time strings (HH:mm:ss:SSS) method

Java timestamps to formatted time strings (HH:mm:ss:SSS) method

Posted on 2025-04-12
Browse:480

How to Convert a Timestamp to a Formatted Time String (HH:mm:ss:SSS) in Java?

Converting Timestamps to Formatted Time in Java

You encounter a common task in programming: converting a timestamp, usually represented as milliseconds since a specific point in time (often the epoch), into a human-readable string. In this case, you specifically want to convert into a format displaying hours, minutes, seconds, and milliseconds (h:m:s:ms).

To achieve this conversion, the first step is to convert the long timestamp into a Date object. This can be done using the constructor Date(long timestamp).

Date date = new Date(logEvent.timestamp);

Next, create a SimpleDateFormat object to specify the desired output format. This format specifies how the date should be formatted, with hours, minutes, seconds, and milliseconds.

DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");

Optionally, you can specify a timezone for the formatter to ensure the time is displayed in the correct timezone.

formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

Finally, you can format the date using the format method of the SimpleDateFormat object.

String dateFormatted = formatter.format(date);

This code will produce a string in the h:m:s:ms format, such as "00:20:00.000" for a timestamp of 1200 milliseconds.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3