Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JodaTime duration to string

I have movie with duration 127 seconds. I wanna display it as 02:07. What is the best way to implement this?

like image 488
fedor.belov Avatar asked May 31 '12 08:05

fedor.belov


2 Answers

Duration yourDuration = //...
Period period = yourDuration.toPeriod();
PeriodFormatter minutesAndSeconds = new PeriodFormatterBuilder()
     .printZeroAlways()
     .appendMinutes()
     .appendSeparator(":")
     .appendSeconds()
     .toFormatter();
String result = minutesAndSeconds.print(period);
like image 152
Ilya Avatar answered Oct 18 '22 02:10

Ilya


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 !

like image 26
Yokich Avatar answered Oct 18 '22 02:10

Yokich