1) Quick response:
String.format( "%03d:%02d", ms / 3600000, ( ms / 60000 ) % 60 );
2) "Traditional" mathematical solution:
Calculating the fields:
Assuming 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 the module: A % B
returns the remainder of the A
by B
;
-
The module was used in segundos
and minutos
to be restricted from 0 to 59;
-
In% with_%, no module has been applied to allow outputs such as horas
, 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 Output:
For output, we use 107:38
with the mask String.format()
, which returns us 3 boxes filled by zero left on the first parameter, and two for the second parameter:
107:38
If you want to add the seconds to the counter, just update "%03d:%02d"
:
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 ) );
Output:
107:38:13
3) Solution using java.util.concurrent.TimeUnit
If the String.format
class is available (Android API 9+), this code can be used (assuming java.util.concurrent.TimeUnit
is the millisecond variable):
String.format("%03d:%02d", TimeUnit.MILLISECONDS.toHours( ms ),
TimeUnit.MILLISECONDS.toMinutes( ms ) % 60 );
I just mentioned that the class exists. It seems an exaggeration to me.