问题

我想使用像H:MM:SS这样的模式来格式化持续时间(以秒为单位)。 java中的当前实用程序旨在格式化时间而不是持续时间。


#1 热门回答(164 赞)

如果你不想在库中拖动,那么使用Formatter或相关的快捷方式就足够了。给定整数秒数s:

String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));

#2 热门回答(59 赞)

我使用Apache common'sDurationFormatUtilslike:

DurationFormatUtils.formatDuration(millis, "**H:mm:ss**", true));

#3 热门回答(58 赞)

如果你使用的是8之前的Java版本,则可以使用Joda TimePeriodFormatter。如果你真的有一个持续时间(即没有参考日历系统的经过时间)那么你应该大部分使用Duration - 你可以调用toPeriod(指定PeriodType你想要反映25小时是否为1天和1小时或不等,以获得aPeriod,你可以格式化。

如果你使用的是Java 8或更高版本:我通常建议使用java.time.Duration来表示持续时间。然后你可以调用getSeconds()之类的东西来获取标准字符串格式的整数,如果需要的话,按照bobince的答案 - 尽管你应该注意持续时间为负的情况,因为你可能想要在输出字符串中作为单一的符号。所以类似于:

public static String formatDuration(Duration duration) {
    long seconds = duration.getSeconds();
    long absSeconds = Math.abs(seconds);
    String positive = String.format(
        "%d:%02d:%02d",
        absSeconds / 3600,
        (absSeconds % 3600) / 60,
        absSeconds % 60);
    return seconds < 0 ? "-" + positive : positive;
}

如果烦人的手动,格式化这种方式是非常简单的。 Forparsingit一般来说变得更难了......当然,如果你愿意,你仍然可以使用Joda Time甚至是Java 8。


原文链接