Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda-Time: Formatting with multiple formats with single Formatter

I'd like to print durations given in milliseconds with different format specification 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 1 hour field digit for durations lower than 10 hours,
but 2 hour field digits when having a leading day 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 had 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)
}

which 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 leading zero of two-digit-day-representation in case (1) but simultaneously force to print it in case (3) with same PeriodFormat.

Is it possible to do that with a single org.joda.time.format.PeriodFormatter?

like image 494
binuWADa Avatar asked Nov 14 '22 01:11

binuWADa


1 Answers

Perhaps not a real answer but meanwhile I'm afraid that you need two PeriodFormatter to solve this task, so manage it with

object JodaTest {
  import org.joda.time._
  import format._
  private def pdf(digits: Int) = new PeriodFormatter(
    new PeriodFormatterBuilder()
      .appendDays.appendSeparator("d ")
      .printZeroAlways
      .minimumPrintedDigits(digits).appendHours.appendSeparator(":")
      .minimumPrintedDigits(2).appendMinutes
      .toPrinter, null)
  private lazy val pdf1 = pdf(1)
  private lazy val pdf2 = pdf(2)
  def durstr(duration: Long): String = {
    val period = new Period(duration).normalizedStandard
    val pdf = if (period.getDays > 0) pdf2 else pdf1
    pdf.print(period)
  }
}

which leads to desired

  2700000 => "0:45"
  4980000 => "1:23"
 43500000 => "12:05"
104940000 => "1d 05:09".
like image 135
binuWADa Avatar answered Dec 10 '22 08:12

binuWADa