Home  >  Article  >  Java  >  How do I Convert Milliseconds to \"hh:mm:ss\" Format in Java?

How do I Convert Milliseconds to \"hh:mm:ss\" Format in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 11:55:30279browse

How do I Convert Milliseconds to

How to Convert Milliseconds to "hh:mm:ss" Format: Resolved

Converting milliseconds to the "hh:mm:ss" format can be tricky, but Java's TimeUnit API provides a convenient way to do so. After stumbling upon an incorrect attempt from another thread, let's explore the right way to tackle this conversion.

Initially, the incorrect approach involved using the line:

TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.MINUTES.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))

However, this calculation erroneously converted hours to milliseconds using minutes instead of hours. The correct logic is:

TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))

Here's a corrected code snippet:

String.format("%02d:%02d:%02d", 
    TimeUnit.MILLISECONDS.toHours(millis),
    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), // Corrected line
    TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));   

This modification ensures that hours are correctly converted using the proper Time Unit.

Furthermore, the code can be simplified 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 approaches leverage the TimeUnit API and provide precise "hh:mm:ss" formatting for milliseconds.

The above is the detailed content of How do I Convert Milliseconds to \"hh:mm:ss\" Format 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