Home > Java > javaTutorial > How to Convert Milliseconds to a Human-Readable Time Format in Java?

How to Convert Milliseconds to a Human-Readable Time Format in Java?

Barbara Streisand
Release: 2024-12-11 00:25:15
Original
373 people have browsed it

How to Convert Milliseconds to a Human-Readable Time Format in Java?

Converting Milliseconds to Human-Readable Time Format in Java

To display time elapsed in a user-friendly format, such as "XX mins, XX seconds", several Java techniques can be utilized.

One option involves the java.util.concurrent.TimeUnit class. TimeUnit provides utilities for converting time between various units, including milliseconds and minutes. The following code snippet demonstrates its usage:

String formattedTime = String.format("%d min, %d sec",
    TimeUnit.MILLISECONDS.toMinutes(millis),
    TimeUnit.MILLISECONDS.toSeconds(millis) -
    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
Copy after login

Note that toMinutes was introduced in Java 1.6. For older versions, use the following equations:

int minutes = (int) ((milliseconds / (1000*60)) % 60);
int seconds = (int) (milliseconds / 1000) % 60;
Copy after login

To add leading zeros for values within the range 0-9, modify the format string as follows:

String formattedTime = String.format("%02d min, %02d sec",
    TimeUnit.MILLISECONDS.toMinutes(millis),
    TimeUnit.MILLISECONDS.toSeconds(millis) -
    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
Copy after login

The above is the detailed content of How to Convert Milliseconds to a Human-Readable Time 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