Home > Java > javaTutorial > body text

How to Convert Millisecond Timestamps to Formatted Time Strings in Java?

Mary-Kate Olsen
Release: 2024-11-12 08:07:01
Original
451 people have browsed it

How to Convert Millisecond Timestamps to Formatted Time Strings in Java?

Converting Millisecond Timestamps to String Formatted Time in Java

As a Java developer, you may encounter scenarios where you need to convert long values representing milliseconds elapsed since the Epoch (1970-01-01T00:00:00Z) into human-readable time strings in a specific format (e.g., h:m:s:ms). This arises frequently when working with timestamps from logging frameworks like log4j.

While you may attempt to use simple division or conversions, such as logEvent.timeStamp/ (1000*60*60) or TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp), they often lead to incorrect results.

To accurately convert milliseconds to the desired time format, follow these steps:

  1. Instantiate a Date object using the timestamp value: Date date = new Date(logEvent.timeStamp);
  2. Create a SimpleDateFormat formatter, specifying the desired format: DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
  3. Set the timezone to UTC for consistent formatting: formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
  4. Format the Date object and store it in a string variable: String dateFormatted = formatter.format(date);

This approach ensures accurate conversion of timestamps to strings in the specified format, enabling you to display or process time-related information effectively.

The above is the detailed content of How to Convert Millisecond Timestamps to Formatted Time Strings 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