I'm confused. After stumbling upon this thread, I tried to figure out how to format a countdown timer that had the format hh:mm:ss
.
Here's my attempt -
//hh:mm:ss
String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.MINUTES.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
So, when I try a value like 3600000ms
, I get 01:59:00
, which is wrong since it should be 01:00:00
. Obviously there's something wrong with my logic, but at the moment, I cannot see what it is!
Can anyone help?
Edit -
Fixed it. Here's the right way to format milliseconds to hh:mm:ss
format -
//hh:mm:ss
String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
The problem was this TimeUnit.MINUTES.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
. It should have been this TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
instead.
See runnable example using input of 1200 ms.
Well, you could try something like this, :
to convert milliseconds to a time value
The answer marked as correct has a little mistake,
for example this is an example of the value that i get:
This is the solution to get the right format is:
getting as a result a correct format:
other option to get the format
hh:mm:ss
is just :The generic method for this is fairly simple: