Home > Java > javaTutorial > 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
Release: 2024-11-02 11:55:30
Original
399 people have browsed it

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))
Copy after login

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))
Copy after login

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)));   
Copy after login

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));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template