Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Milliseconds to "X mins, x seconds" in Java?

Tags:

java

time

I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current System.currentTimeMillis() from the start variable, and I want to show them the time elapsed using a human readable format such as "XX hours, XX mins, XX seconds" or even "XX mins, XX seconds" because its not likely to take someone an hour.

What's the best way to do this?

like image 388
Ali Avatar asked Mar 09 '09 08:03

Ali


People also ask

How do you convert milliseconds to minutes and seconds in Java?

Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60). Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60).

How do you convert milliseconds to hours min sec format in Java?

toSeconds(); String hhmmss = String. format("%02d:%02d:%02d", hours, minutes, seconds); System. out. println(hhmmss);

How do you convert milliseconds into hours minutes and seconds?

To convert milliseconds to hours, minutes, seconds:Divide the milliseconds by 1000 to get the seconds. Divide the seconds by 60 to get the minutes. Divide the minutes by 60 to get the hours. Add a leading zero if the values are less than 10 to format them consistently.


1 Answers

Use the java.util.concurrent.TimeUnit class:

String.format("%d min, %d sec",      TimeUnit.MILLISECONDS.toMinutes(millis),     TimeUnit.MILLISECONDS.toSeconds(millis) -      TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)) ); 

Note: TimeUnit is part of the Java 1.5 specification, but toMinutes was added as of Java 1.6.

To add a leading zero for values 0-9, just do:

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

If TimeUnit or toMinutes are unsupported (such as on Android before API version 9), use the following equations:

int seconds = (int) (milliseconds / 1000) % 60 ; int minutes = (int) ((milliseconds / (1000*60)) % 60); int hours   = (int) ((milliseconds / (1000*60*60)) % 24); //etc... 
like image 62
siddhadev Avatar answered Sep 21 '22 03:09

siddhadev