我想用H:MM:SS这样的模式以秒为单位格式化持续时间。java中当前的实用程序设计用于格式化时间,而不是持续时间。
当前回答
我使用Apache common的DurationFormatUtils,就像这样:
DurationFormatUtils.formatDuration(millis, "**H:mm:ss**", true);
其他回答
查看所有这些计算,大多数单位(小时、分钟等)都有一个. tofoopart()方便方法,这可能是有帮助的。
E.g.
Duration.ofMinutes(110L).toMinutesPart() == 50
读:到父单位(小时)的下一个值的分钟数。
有一个相当简单和优雅的方法,至少在24小时内:
DateTimeFormatter.ISO_LOCAL_TIME.format(value.addTo(LocalTime.of(0, 0)))
格式化程序需要一个时态对象来格式化,因此可以通过将持续时间添加到LocalTime为00:00(即午夜)来创建一个时态对象。这将为您提供一个LocalTime,表示从午夜到该时间的持续时间,然后很容易将其格式化为标准HH:mm:ss表示法。这样做的优点是不需要外部库,并且使用java。时间库做计算,而不是手动计算小时、分、秒。
在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)
这是一个可行的选择。
public static String showDuration(LocalTime otherTime){
DateTimeFormatter df = DateTimeFormatter.ISO_LOCAL_TIME;
LocalTime now = LocalTime.now();
System.out.println("now: " + now);
System.out.println("otherTime: " + otherTime);
System.out.println("otherTime: " + otherTime.format(df));
Duration span = Duration.between(otherTime, now);
LocalTime fTime = LocalTime.ofNanoOfDay(span.toNanos());
String output = fTime.format(df);
System.out.println(output);
return output;
}
使用
System.out.println(showDuration(LocalTime.of(9, 30, 0, 0)));
产生如下内容:
otherTime: 09:30
otherTime: 09:30:00
11:31:27.463
11:31:27.463
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())));