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!