Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatted string from JodaTime duration

Tags:

java

jodatime

I am trying to get formatted string from JodaTime's duration class.

Duration duration = new Duration(durationInSecond * 1000);
PeriodFormatter formatter = new PeriodFormatterBuilder()
                .appendDays()
                .appendSuffix(" days, ")
                .appendHours()
                .appendSuffix(" hours, ")
                .appendMinutes()
                .appendSuffix(" minutes and ")
                .appendSeconds()
                .appendSuffix(" seconds")
                .toFormatter();
String formattedString = formatter.print(duration.toPeriod());

Value of formattedString should be

65 days, 3 hours, 5 minutes and 20 seconds

But It is

1563 hours, 5 minutes, 20 seconds

1563 hours are 65 days and 3 hours but formatter is not printing in that manner.

What I'm missing here?

like image 449
Rohit Gupta Avatar asked Sep 06 '26 13:09

Rohit Gupta


2 Answers

You may use a PeriodType along with Period.normalizedStandard(org.joda.time.PeriodType) to specify which fields you are interested in.

In your case PeriodType.dayTime()seems appropriate .

Duration duration = new Duration(durationInSecond * 1000);
PeriodFormatter formatter = new PeriodFormatterBuilder()
        .appendDays()
        .appendSuffix(" days, ")
        .appendHours()
        .appendSuffix(" hours, ")
        .appendMinutes()
        .appendSuffix(" minutes, ")
        .appendSeconds()
        .appendSuffix(" seconds")
        .toFormatter();

Period period = duration.toPeriod();
Period dayTimePeriod = period.normalizedStandard(PeriodType.dayTime());
String formattedString = formatter.print(dayTimePeriod);

System.out.println(formattedString);
like image 195
Arnaud Avatar answered Sep 08 '26 02:09

Arnaud


I found using PeriodFormat.getDefault() helpful for creating the PeriodFormatter, without having to do all the extra work using the PeriodFormatterBuilder and creating your own. It gives the same result.

like image 25
Roy Wood Avatar answered Sep 08 '26 03:09

Roy Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!