I would like to print durations given in milliseconds with different format specifications depending on its size:
case (1) "H:mm" if duration < 10 hours
case (2) "HH:mm" if duration < 24 hours
case (3) "#d HH:mm" else (duration >= 24 hours)
which means only a 1-hour field digit for less than 10 hours, but 2-hour field digits if there is an initial daily field!
Examples:
case (1) "0:45" means 45 minutes,
"1:23" means 1 hour and 23 minutes,
case (2) "12:05" means 12 hours and 5 minutes and
case (3) "1d 05:09" means 1 day, 5 hours and 9 minutes
(= 29 hours and 9 minutes).
I tried with
object JodaTest {
import org.joda.time._
private val pdf = {
import format._
val pfb = new PeriodFormatterBuilder()
.appendDays.appendSeparator("d ")
.printZeroAlways
.minimumPrintedDigits(2).appendHours.appendSeparator(":")
.appendMinutes
new PeriodFormatter(pfb.toPrinter, null)
}
def durstr(duration: Long): String =
pdf.print((new Period(duration)).normalizedStandard)
}
that leads to
2700000 => "00:45" but should be "0:45"
4980000 => "01:23" but should be "1:23"
43500000 => "12:05"
104940000 => "1d 05:09"
but I donβt know how to omit the initial zero of the two-digit representation of the day in case (1), but at the same time I am forced to print it in case (3) with the same period.
Is it possible to do this with one org.joda.time.format.PeriodFormatter?
source
share