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!