Search code examples
javajava-8datetime-formatjava-timeduration

How do i format a java.time.Duration mm:ss


I have a java.time.Duration and I want to output it in the form of mm:ss. It doesnt seem possible to use DateTimeFormatter since that only accepts LocalTime, ZonedTime etc.

So I did it like this, works fine for 90 seconds give 1:30, but for 66 seconds gives 1:6 whereas I want 1:06

Duration duration = Duration.ofSeconds(track.getLength().longValue());
System.out.println(duration.toMinutes() + ":" + 
          duration.minusMinutes(duration.toMinutes()).getSeconds());

Solution

  • You could create a LocalTime representing the duration from midnight (00:00) and use a DateTimeFormatter:

    LocalTime t = LocalTime.MIDNIGHT.plus(duration);
    String s = DateTimeFormatter.ofPattern("m:ss").format(t);
    

    Note that this will only work for durations less than one hour.