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:
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!