Home > Java > javaTutorial > body text

How to Convert Milliseconds to \'hh:mm:ss\' Format in Java?

Mary-Kate Olsen
Release: 2024-11-01 19:09:30
Original
246 people have browsed it

How to Convert Milliseconds to

Formatting Milliseconds to "hh:mm:ss"

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

while it should have been:

TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
Copy after login

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

Test Case:

long millis = 3600000;
String hms = ... // Replace with revised code from above

System.out.println(hms); // Expected output: 01:00:00
Copy after login

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!