Converting Milliseconds to "hh:mm:ss" Format
You may encounter a situation where you need to convert milliseconds to the familiar "hh:mm:ss" format, typically used for representing time. This can be a common requirement in applications, such as countdown timers.
Understanding the Problem
You may have tried using the following code to perform the conversion:
<code class="java">//hh:mm:ss String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.MINUTES.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));</code>
However, this code might not be working as expected. For instance, for an input of 3600000ms (representing 1 hour), you get "01:59:00" instead of the correct "01:00:00".
Identifying the Issue
Upon closer examination, the issue lies in this line:
<code class="java">TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.MINUTES.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))</code>
Here, you are converting hours to milliseconds using minutes instead of hours.
Correcting the Logic
The correct code should use TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)) instead:
<code class="java">//hh:mm:ss 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)));</code>
This change ensures that the time conversion is done correctly, and you will get the desired result of "01:00:00" for 3600000ms.
Simplified Version
You can further simplify the code by using a modulus division instead of subtraction:
<code class="java">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));</code>
This version remains efficient while providing the same accurate results.
The above is the detailed content of How to Convert Milliseconds to \"hh:mm:ss\" Format?. For more information, please follow other related articles on the PHP Chinese website!