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

2018-12-31 14:12发布

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.

15条回答
临风纵饮
2楼-- · 2018-12-31 15:15

This answer only uses Duration methods and works with Java 8 :

public static String format(Duration d) {
    long days = d.toDays();
    d = d.minusDays(days);
    long hours = d.toHours();
    d = d.minusHours(hours);
    long minutes = d.toMinutes();
    d = d.minusMinutes(minutes);
    long seconds = d.getSeconds() ;
    return 
            (days ==  0?"":days+" jours,")+ 
            (hours == 0?"":hours+" heures,")+ 
            (minutes ==  0?"":minutes+" minutes,")+ 
            (seconds == 0?"":seconds+" secondes,");
}
查看更多
倾城一夜雪
3楼-- · 2018-12-31 15:16

If you don't want to drag in libraries, it's simple enough to do yourself using a Formatter, or related shortcut eg. given integer number of seconds s:

  String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));
查看更多
倾城一夜雪
4楼-- · 2018-12-31 15:17

I use Apache common's DurationFormatUtils like so:

DurationFormatUtils.formatDuration(millis, "**H:mm:ss**", true);
查看更多
登录 后发表回答