Duration timeLeft = Duration.ofMillis(3600000);
String hhmmss = String.format("%02d:%02d:%02d",
timeLeft.toHours(), timeLeft.toMinutesPart(), timeLeft.toSecondsPart());
System.out.println(hhmmss);
This prints:
01:00:00
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, its Duration
class does it more elegantly and in a less error-prone way than TimeUnit
.
The toMinutesPart
and toSecondsPart
methods I used were introduced in Java 9.
long hours = timeLeft.toHours();
timeLeft = timeLeft.minusHours(hours);
long minutes = timeLeft.toMinutes();
timeLeft = timeLeft.minusMinutes(minutes);
long seconds = timeLeft.toSeconds();
String hhmmss = String.format("%02d:%02d:%02d", hours, minutes, seconds);
System.out.println(hhmmss);
The output is the same as above.
java.time
comes built-in.org.threeten.bp
with subpackages.java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).