我想用H:MM:SS这样的模式以秒为单位格式化持续时间。java中当前的实用程序设计用于格式化时间,而不是持续时间。


当前回答

我的库Time4J提供了一个基于模式的解决方案(类似于Apache DurationFormatUtils,但更灵活):

Duration<ClockUnit> 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

这段代码演示了处理小时溢出和符号处理的功能,请参见基于模式的持续时间格式化程序的API。

其他回答

那么下面的函数呢 + H: MM: SS 或 + H: MM: SS.sss

public static String formatInterval(final long interval, boolean millisecs )
{
    final long hr = TimeUnit.MILLISECONDS.toHours(interval);
    final long min = TimeUnit.MILLISECONDS.toMinutes(interval) %60;
    final long sec = TimeUnit.MILLISECONDS.toSeconds(interval) %60;
    final long ms = TimeUnit.MILLISECONDS.toMillis(interval) %1000;
    if( millisecs ) {
        return String.format("%02d:%02d:%02d.%03d", hr, min, sec, ms);
    } else {
        return String.format("%02d:%02d:%02d", hr, min, sec );
    }
}

有一个相当简单和优雅的方法,至少在24小时内:

DateTimeFormatter.ISO_LOCAL_TIME.format(value.addTo(LocalTime.of(0, 0)))

格式化程序需要一个时态对象来格式化,因此可以通过将持续时间添加到LocalTime为00:00(即午夜)来创建一个时态对象。这将为您提供一个LocalTime,表示从午夜到该时间的持续时间,然后很容易将其格式化为标准HH:mm:ss表示法。这样做的优点是不需要外部库,并且使用java。时间库做计算,而不是手动计算小时、分、秒。

下面是在Kotlin中将java.time.Duration转换为一个漂亮的字符串的一行代码:

duration.run {
   "%d:%02d:%02d.%03d".format(toHours(), toMinutesPart(), toSecondsPart(), toMillisPart())
}

示例输出: 120:56:03.004

long duration = 4 * 60 * 60 * 1000;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault());
log.info("Duration: " + sdf.format(new Date(duration - TimeZone.getDefault().getRawOffset())));

在scala中(我看到了一些其他的尝试,并没有留下深刻的印象):

def formatDuration(duration: Duration): String = {
  import duration._ // get access to all the members ;)
  f"$toDaysPart $toHoursPart%02d:$toMinutesPart%02d:$toSecondsPart%02d:$toMillisPart%03d"
}

看起来很可怕,是吗?好吧,这就是为什么我们使用ide来编写这些东西,以便方法调用($toHoursPart等)是不同的颜色。

f"…"是一个printf/String。格式样式字符串插补器(它允许$ code注入工作) 给定输出1 14:06:32.583,f插值的字符串将等效于string。格式(“1% 02 d: % 2 d: % 2 d。%03d", 14,6,32,583)