I'm using a Period to get a time difference between two DateTimes.
Period p = new Period(startDate, endDate,
PeriodType.standard().withSecondsRemoved().withMillisRemoved());
return PeriodFormat.getDefault().print(p);
That gives me something in the form of "1 hour and 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...?
You can use a PeriodFormatterBuilder.
Something along the lines of:
PeriodFormatter formatter = new PeriodFormatterBuilder()
.minimumPrintedDigits(2)
.printZeroAlways()
.appendHours()
.appendSeparator(":")
.appendMinutes()
.toFormatter();
will give you a formatter which you can then use instead of the default one you're currently using, and I think it will give you something similar to the format you're looking for. You can of course append other fields if you're interested in them.
And changing or skipping the calls to minimumPrintedDigits and printZeroAlways might be able to make it not display the hours part if it's zero and/or display it without leading zeros.
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