1) Rapid response:
String.format( "%03d:%02d", ms / 3600000, ( ms / 60000 ) % 60 );
2) Mathematical "traditional" solution:
Calculating the fields:
Supposing ms
is the millisecond variable:
segundos = ( ms / 1000 ) % 60; // se não precisar de segundos, basta remover esta linha.
minutos = ( ms / 60000 ) % 60; // 60000 = 60 * 1000
horas = ms / 3600000; // 3600000 = 60 * 60 * 1000
System.out.println( String.format( "%03d:%02d", horas, minutos ) );
The operator %
is called module (actually is "split rest", are not synonyms): A % B
returns the rest of the A
for B
;
The %
was used in segundos
and minutos
so that they were restricted from 0 to 59;
In horas
, was not applied %
to allow exits as 107:38
, for example.
If you want, you can add a new line to calculate the days using the same logic:
segundos = ( ms / 1000 ) % 60;
minutos = ( ms / 60000 ) % 60; // 60000 = 60 * 1000
horas = ( ms / 3600000 ) % 24; // 3600000 = 60 * 60 * 1000
dias = ms / 86400000 // 86400000 = 24 * 60 * 60 * 1000
Formatting the output:
To the exit, we use the String.format()
with the mask "%03d:%02d"
, which returns us 3 squares filled by zero left in the first parameter, and two for the second:
107:38
If you want to add seconds to the counter, simply update the String.format
:
segundos = ( ms / 1000 ) % 60;
minutos = ( ms / 60000 ) % 60; // 60000 = 60 * 1000
horas = ms / 3600000; // 3600000 = 60 * 60 * 1000
System.out.println( String.format( "%03d:%02d:%02d", horas, minutos,segundos ) );
Exit:
107:38:13
3) Solution using java.util.Concurrent.Timeunit
Case the class java.util.concurrent.TimeUnit
is available (Android API 9+), can be used this code (assuming that ms
is the millisecond variable):
String.format("%03d:%02d", TimeUnit.MILLISECONDS.toHours( ms ),
TimeUnit.MILLISECONDS.toMinutes( ms ) % 60 );
I mentioned just to comment that the class exists. I think this alternative seems an exaggeration.
Very good your answer! But, because seems to you an exaggeration the use of the Timeunit, and why is using % 60? I found that in the case of the Timeunit it already converted
– felipe.rce
@Felipe.rce First for the needlessness of making the program flow to another class that in the end will just do the calculations anyway, plus the overhead of the calls. By doing the calculation yourself, as it is simple, you arrive at the same result with much less machine operations. As for the 60 %, it is worth remembering that 37200000ms would turn 62 minutes, because the hours are not being discounted, and what we want is 001:02 and not 001:62.
– Bacco