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.
Going by Bohemian's answer we need need not use TimeUnit to find a known value. Much more optimal code would be
Hope it helps
Java 9
This prints:
You are doing right in letting library methods do the conversions involved for you.
java.time
, the modern Java date and time API, or more precisely, itsDuration
class does it more elegantly and in a less error-prone way thanTimeUnit
.The
toMinutesPart
andtoSecondsPart
methods I used were introduced in Java 9.Java 6, 7 and 8
The output is the same as above.
Question: How can that work in Java 6 and 7?
java.time
comes built-in.org.threeten.bp
with subpackages.Links
java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Test results for the 4 implementations
Having to do a lot of formatting for huge data, needed the best performance, so here are the (surprising) results:
for (int i = 0; i < 1000000; i++) { FUNCTION_CALL }
Durations:
formatTimeUnit: 2216 millis
Format: 00:00:00.000
Example: 615605 Millisecend
00:10:15.605
this worked for me, with kotlin