Skip to content

Instantly share code, notes, and snippets.

@fernandomora
Last active October 22, 2021 21:32
Show Gist options
  • Save fernandomora/fe20dab23a25290b4be707e6d54a3b52 to your computer and use it in GitHub Desktop.
Save fernandomora/fe20dab23a25290b4be707e6d54a3b52 to your computer and use it in GitHub Desktop.
Helper to pretty print scala Duration
package com.intenthq.elasticsearchwriter.duration
import java.util.Locale
import java.util.concurrent.TimeUnit
import scala.concurrent.duration._
object PrettyDuration {
private val abbreviate = Map(
NANOSECONDS -> "ns",
MICROSECONDS -> "μs",
MILLISECONDS -> "ms",
SECONDS -> "s",
MINUTES -> "min",
HOURS -> "h",
DAYS -> "d"
)
private val units = TimeUnit.values.reverse
implicit class PrettyPrintableDuration(duration: Duration) {
def pretty: String = pretty()
def pretty(precision: Int = 4): String = duration match {
case d: FiniteDuration =>
val chosenUnit = units.find(_.convert(d.length, d.unit) > 0).getOrElse(NANOSECONDS)
val value = d.toUnit(chosenUnit)
s"%.${precision}g %s".formatLocal(Locale.ROOT, value, abbreviate(chosenUnit))
case Duration.MinusInf => s"-∞ (minus infinity)"
case Duration.Inf => s"∞ (infinity)"
case _ => s"undefined"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment