Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to format a duration in hours and minutes

Short answer

Create a Duration and take its parts with the to...Part() methods:

void main() {
    Duration duration = Duration.ofSeconds(3909);
 
    String text = "%02d:%02d:%02d".formatted(
            duration.toHours(), duration.toMinutesPart(), duration.toSecondsPart());
    IO.println(text);
}

Output:

01:05:09

In words

Skip zero parts to get "2 h 5 min":

String humanize(Duration d) {
    var parts = new ArrayList<String>();
    if (d.toDays() > 0) parts.add(d.toDays() + " d");
    if (d.toHoursPart() > 0) parts.add(d.toHoursPart() + " h");
    if (d.toMinutesPart() > 0) parts.add(d.toMinutesPart() + " min");
    return parts.isEmpty() ? "less than a minute" : String.join(" ", parts);
}
 
void main() {
    IO.println(humanize(Duration.ofMinutes(125)));
    IO.println(humanize(Duration.ofHours(50)));
    IO.println(humanize(Duration.ofSeconds(20)));
}

Output:

2 h 5 min
2 d 2 h
less than a minute

The standard notation

Duration.toString() prints the ISO 8601 format, and Duration.parse() reads it:

void main() {
    IO.println(Duration.ofMinutes(95));
    IO.println(Duration.parse("PT1H30M").toMinutes());
}

Output:

PT1H35M
90

Common mistake

Using toMinutes() instead of toMinutesPart(). The first returns all the minutes, not the remainder after hours:

void main() {
    Duration d = Duration.ofMinutes(125);
 
    IO.println(d.toHours() + ":" + d.toMinutes());
    IO.println(d.toHours() + ":" + d.toMinutesPart());
}

Output:

2:125
2:5

Functions used in this recipe

  • Duration — An amount of time in seconds and nanoseconds — hours, minutes, seconds.

Thanks for reading!

Donate to the site — we work hard for you.