Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ectera

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());
like image 329
Paul Taylor Avatar asked Feb 23 '15 13:02

Paul Taylor


1 Answers

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.

like image 120
assylias Avatar answered Sep 24 '22 16:09

assylias