Joda DateTime difference with PeriodFormat as 1:30

I use a period to get the time difference between two DateTimes.

 Period p = new Period(startDate, endDate,
                PeriodType.standard().withSecondsRemoved().withMillisRemoved());

        return PeriodFormat.getDefault().print(p);

It gives me something in the form of "1 hour 30 minutes."

How can I get something like "1:30" or ": 15"?

I suppose I could do something like:

public static int getHoursDifference(DateTime startDate, DateTime endDate) {
        Period p = new Period(startDate, endDate);
        return p.getHours();
    }

And similarly for minutes, and then concatenate ...?

+3
source share
1 answer

You can use PeriodFormatterBuilder .

Something along the lines of:

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

will provide you with a formatter that you can use instead of the standard one you are currently using, and I think that it will give you something similar to the format you are looking for. You can, of course, add other fields if you are interested in them.

minimumPrintedDigits printZeroAlways , / .

+4

All Articles