I have movie with duration 127 seconds. I wanna display it as 02:07. What is the best way to implement this?
Asked
Active
Viewed 1.2k times
27
fedor.belov
- 20,963
- 25
- 85
- 125
-
1I have temporary implemented this with `org.apache.commons.lang.time.DurationFormatUtils` – fedor.belov Jun 01 '12 at 08:57
-
Related: http://stackoverflow.com/questions/1440557/joda-time-period-to-string – ripper234 May 06 '13 at 08:51
2 Answers
32
Duration yourDuration = //...
Period period = yourDuration.toPeriod();
PeriodFormatter minutesAndSeconds = new PeriodFormatterBuilder()
.printZeroAlways()
.appendMinutes()
.appendSeparator(":")
.appendSeconds()
.toFormatter();
String result = minutesAndSeconds.print(period);
Ilya
- 28,466
- 18
- 106
- 153
26
I wanted this for myself and I did not find llyas answer to be accurate.
I want to have a counter and when I had 0 hours and 1 minute I got 0:1 with his answer- but this is fixed easily with one line of code!
Period p = time.toPeriod();
PeriodFormatter hm = new PeriodFormatterBuilder()
.printZeroAlways()
.minimumPrintedDigits(2) // gives the '01'
.appendHours()
.appendSeparator(":")
.appendMinutes()
.toFormatter();
String result = hm.print(p);
This will give you 02:07 !
Yokich
- 1,117
- 1
- 16
- 30
-
1This does seem to work better and I would upvote in preference to the accepted answer – Brian Agnew Oct 22 '15 at 12:38
-
I agree with Brian, the `minimumPrintedDigits(2)` was exactly what I needed. – Amos M. Carpenter Nov 26 '15 at 00:04