Problem:
A developer working with a countdown timer encounters difficulty converting milliseconds to the desired "hh:mm:ss" format. Their initial attempt resulted in incorrect time display, particularly for values exceeding an hour.
Solution:
The main issue stemmed from a logical flaw in converting hours to milliseconds using minutes instead of hours. Specifically, the code utilized:
TimeUnit.MINUTES.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
while it should have been:
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
Code Demonstration:
Here's a revised code snippet that correctly formats milliseconds to "hh:mm:ss":
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
Test Case:
long millis = 3600000; String hms = ... // Replace with revised code from above System.out.println(hms); // Expected output: 01:00:00
Additionally, the code can be optimized using modulus division instead of subtraction:
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1), TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));
Both variations achieve the correct "hh:mm:ss" formatting and leverage the TimeUnit API to handle conversions seamlessly.
The above is the detailed content of How to Convert Milliseconds to \'hh:mm:ss\' Format in Java?. For more information, please follow other related articles on the PHP Chinese website!