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

前端 未结 19 1927
情话喂你
情话喂你 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:30

    This is easier since Java 9. A Duration still isn’t formattable, but methods for getting the hours, minutes and seconds are added, which makes the task somewhat more straightforward:

        LocalDateTime start = LocalDateTime.of(2019, Month.JANUARY, 17, 15, 24, 12);
        LocalDateTime end = LocalDateTime.of(2019, Month.JANUARY, 18, 15, 43, 33);
        Duration diff = Duration.between(start, end);
        String hms = String.format("%d:%02d:%02d", 
                                    diff.toHours(), 
                                    diff.toMinutesPart(), 
                                    diff.toSecondsPart());
        System.out.println(hms);
    

    The output from this snippet is:

    24:19:21

提交回复
热议问题