Reputation: 1378
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?
Upvotes: 3
Views: 2601
Reputation: 6417
PeriodFormat.wordBased
is same as PeriodFormat.getDefault()
but accept Locale
param.
import java.util.Locale
import org.joda.time.Duration
import org.joda.time.PeriodType
import org.joda.time.format.PeriodFormat
PeriodFormat.wordBased(
Locale("en"))
.print(
Duration(1653419081151L)
.toPeriod()
.normalizedStandard(
// PeriodType.standard() // 2733 weeks, 5 days, 19 hours, 4 minutes, 41 seconds and 151 milliseconds
// PeriodType.dayTime() // 19136 days, 19 hours, 4 minutes, 41 seconds and 151 milliseconds
// PeriodType.weeks() // 2733 weeks
PeriodType.days() // 19136 days
)
)
will give you proper output in the preferred language.
Or use own PeriodType
:
normalizedStandard(
PeriodType.forFields(
arrayOf(
DurationFieldType.years(),
DurationFieldType.months(),
DurationFieldType.days(),
DurationFieldType.hours(),
DurationFieldType.minutes()
)
)
Upvotes: 0
Reputation: 79
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.
Upvotes: 3
Reputation: 17534
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);
Upvotes: 4