Home > Java > javaTutorial > How to Convert a Millisecond Timestamp to HH:mm:ss:SSS Format in Java?

How to Convert a Millisecond Timestamp to HH:mm:ss:SSS Format in Java?

Linda Hamilton
Release: 2024-11-13 12:53:02
Original
622 people have browsed it

How to Convert a Millisecond Timestamp to HH:mm:ss:SSS Format in Java?

Converting Millisecond Timestamp to Formatted Time in Java

In Java, converting a timestamp represented as a long value (milliseconds elapsed since Epoch) to a formatted time string in the h:m:s:ms format is a straightforward process.

To achieve this, you can utilize the Date and SimpleDateFormat classes. The Date class represents a specific instant in time, while SimpleDateFormat allows you to format that time according to a given pattern.

Below is a step-by-step solution to your problem:

// Create a Date object from the timestamp
Date date = new Date(logEvent.timeStamp);

// Create a SimpleDateFormat object with the desired time format
DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");

// Set the SimpleDateFormat time zone to UTC for correct time formatting
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

// Format the Date object and convert it to a string
String dateFormatted = formatter.format(date);

// Display the formatted time string
System.out.println(dateFormatted); // Prints time in h:m:s:ms format
Copy after login

This approach ensures accurate conversion of the timestamp to the desired formatted time string.

The above is the detailed content of How to Convert a Millisecond Timestamp to HH:mm:ss:SSS Format 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