Home >Java >javaTutorial >How to Convert Timestamp in Milliseconds to Human-Readable Time in Java?

How to Convert Timestamp in Milliseconds to Human-Readable Time in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-11-20 12:46:14985browse

How to Convert Timestamp in Milliseconds to Human-Readable Time in Java?

Convert Timestamp in Milliseconds to Human-Readable Time in Java

When working with timestamps, it's often necessary to convert them from their raw format (number of milliseconds elapsed from the Epoch) into a more readable string representation. In particular, we may want to convert a long timestamp into a formatted time string with hours, minutes, seconds, and milliseconds.

To achieve this conversion in Java, consider the following approach:

long timestamp = 1200; // Example timestamp in milliseconds

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

// Create a SimpleDateFormat object to format the date
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");

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

// Format the date and store it in a string
String formattedTime = formatter.format(date);

// Print the formatted time
System.out.println(formattedTime);

This code will produce the output "00:00:01.200" for the input timestamp of 1200 milliseconds. The SimpleDateFormat class allows for customization of the output format string to meet your specific requirements. For example, "hh:mm:ss a" would format the time as "12:00:00 PM".

The above is the detailed content of How to Convert Timestamp in Milliseconds to Human-Readable Time 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