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?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With