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

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 04:13:02681browse

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.

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!

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