Home > Java > javaTutorial > body text

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

Barbara Streisand
Release: 2024-11-12 04:13:02
Original
634 people have browsed it

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);
Copy after login

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");
Copy after login

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

formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Copy after login

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

String dateFormatted = formatter.format(date);
Copy after login

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.

The above is the detailed content of How to Convert a Timestamp to a Formatted Time String (HH:mm:ss:SSS) 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