Search code examples
javaformattingjodatimeperiod

PeriodFormatter - How to prepend 0s if the hours or minutes happens to be a single digit number?


When I use PeriodFormatter as below

PeriodFormatter formatter = new PeriodFormatterBuilder().appendHours()
                .appendLiteral(":").appendMinutes().appendLiteral(":")
                .appendSeconds().toFormatter();

I get the output as 4:39:9 Which means 4 hrs 39 mins and 9 seconds.

How to modify the formatter to produce 04:39:09? Thanks


Solution

  • Add .printZeroAlways() and .minimumPrintedDigits(2):

        PeriodFormatter formatter = new PeriodFormatterBuilder()
            .printZeroAlways()
            .minimumPrintedDigits(2)
            .appendHours()
            .appendLiteral(":")
            .appendMinutes()
            .appendLiteral(":")
            .appendSeconds()
            .toFormatter();