How to format a duration in java? (e.g format H:MM:SS)

前端 未结 19 1506
情话喂你
情话喂你 2020-11-22 03:32

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.

19条回答
  •  粉色の甜心
    2020-11-22 04:29

    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.

提交回复
热议问题