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)) );
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;
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)) );
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!