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.
My library Time4J offers a pattern-based solution (similar to Apache DurationFormatUtils
, but more flexible):
Duration duration =
Duration.of(-573421, ClockUnit.SECONDS) // input in seconds only
.with(Duration.STD_CLOCK_PERIOD); // performs normalization to h:mm:ss-structure
String fs = Duration.formatter(ClockUnit.class, "+##h:mm:ss").format(duration);
System.out.println(fs); // output => -159:17:01
This code demonstrates the capabilities to handle hour overflow and sign handling, see also the API of duration-formatter based on pattern.