I\'d like to format a duration in seconds using a pattern like H:MM:SS. The current utilities in java are designed to format a time but not a duration.
In scala (I saw some other attempts, and wasn't impressed):
def formatDuration(duration: Duration): String = {
import duration._ // get access to all the members ;)
f"$toDaysPart $toHoursPart%02d:$toMinutesPart%02d:$toSecondsPart%02d:$toMillisPart%03d"
}
Looks horrible yes? Well that's why we use IDEs to write this stuff so that the method calls ($toHoursPart
etc) are a different color.
The f"..."
is a printf
/String.format
style string interpolator (which is what allows the $
code injection to work)
Given an output of 1 14:06:32.583
, the f
interpolated string would be equivalent to String.format("1 %02d:%02d:%02d.%03d", 14, 6, 32, 583)