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


当前回答

这是一个可行的选择。

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

其他回答

我使用Apache common的DurationFormatUtils,就像这样:

DurationFormatUtils.formatDuration(millis, "**H:mm:ss**", true);
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())));

从Java 9开始,这变得更容易了。Duration仍然是不可格式化的,但是添加了获取小时、分钟和秒的方法,这使得任务更简单:

    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);

这个代码片段的输出是:

24:19:21

有一个相当简单和优雅的方法,至少在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