Search code examples
javaformattingjodatimeperiod

Showing period with days, hours, minutes and seconds


I have the following period 1month 5d 22h 35m 39s, which I want to format as 35d 22h 35m 39s. However when using the following formatter the months are just removed and haven't been added to the days:

PeriodFormatter formatter = new PeriodFormatterBuilder()
    .printZeroAlways()
    .appendDays().appendSuffix(" d ")
    .appendHours().appendSuffix(" h ")
    .appendMinutes().appendSuffix(" m ")
    .appendSeconds().appendSuffix(" s ")
    .toFormatter();

After some searching I found that one is supposed to use the normalizedStandard() method on Period, but when using it with period.normalizedStandard(PeriodType.dayTime()) I am getting the following error:

java.lang.UnsupportedOperationException: Field is not supported
    at org.joda.time.PeriodType.setIndexedField(PeriodType.java:690)
    at org.joda.time.Period.withMonths(Period.java:851)
    at org.joda.time.Period.normalizedStandard(Period.java:1541)
    at amadeus.bid.wicket.markup.html.CountDownLabel.onComponentTagBody(CountDownLabel.java:34)

Any ideas?


Solution

  • I don't think it will be possible to reliably convert a set number of months in a period back to days because the number of days in a month varies.

    Example:

    //From: 1month 5d 22h 35m 39s
    Period period = new Period(0, 1, 0, 5, 22, 35, 39, 0);
    //To: 35d 22h 35m 39s.
    period.toStandardDays();
    

    Throws the following exception: java.lang.UnsupportedOperationException: Cannot convert to Days as this period contains months and months vary in length