Home  >  Article  >  Java  >  How to Convert Millisecond Timestamps to Human-Readable Time Strings in Java?

How to Convert Millisecond Timestamps to Human-Readable Time Strings in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 22:59:02271browse

How to Convert Millisecond Timestamps to Human-Readable Time Strings in Java?

Converting Millisecond Timestamps to Human-Readable Time Strings in Java

When working with timestamped data, the need often arises to convert a long integer representing the number of milliseconds since the Epoch (January 1, 1970) into a more readable and informative format, such as "h:m:s:ms" (hours:minutes:seconds:milliseconds).

In the context of log4j, retrieving a timestamp from a logging event can be achieved through the logEvent.timeStamp field. However, converting this timestamp to a formatted time can be challenging.

Incorrect Approaches:

Attempts to convert the milliseconds directly using operations like dividing by the number of seconds in an hour or using the TimeUnit.MILLISECONDS.toMinutes() method will yield incorrect results, as the conversion process involves more than simple arithmetic.

Correct Solution:

To accurately convert a millisecond timestamp to a formatted time string, we can utilize Java's built-in date and time formatting capabilities:

Date date = new Date(logEvent.timeStamp);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateFormatted = formatter.format(date);

This example demonstrates the conversion process:

  • new Date() creates a Date object from the millisecond value.
  • SimpleDateFormat creates a formatter with a specific date pattern ("HH:mm:ss.SSS" for hours, minutes, seconds, and milliseconds).
  • The formatter's time zone is set to UTC (Coordinated Universal Time) to ensure consistent formatting.
  • formatter.format(date) returns the formatted time as a string.

Other Formatting Options:

The Java API provides a variety of SimpleDateFormat date patterns to support different formatting styles. Here are some common options:

Pattern Output
"h:m:s:ms" 03:34:56:123
"EEE, MMM d, yyyy hh:mm:ss a" Wed, Mar 17, 2023 03:34:56 PM
"yyyy-MM-dd HH:mm:ss.SSS" 2023-03-17 15:34:56.123

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