获取 Java LocalDateTime 的时差并将其转换为字符串格式

Getting a time difference in Java LocalDateTime and converting it to String format

我正在计算两个 LocalDateTime 值之间的时间差。为此,我正在使用 Duration。现在我想将其转换为 hh:mm:ss 格式作为字符串值。我一直在检查如何做到这一点,但仍然没有运气。任何指导将不胜感激。

 LocalDateTime startTime = some value
 LocalDateTime endTime = some value
 Duration totalWaitingDuration = Duration.between(endTime, startTime);
 String waitingTime = String.valueOf(totalWaitingDuration.toHours()); 

在这里,我只得到以小时为单位的时差。我怎样才能得到它的 hh:mm:ss 格式?

您可以使用 apache commons:

DurationFormatUtils.formatDuration(totalWaitingDuration.toMillis(), "H:mm:ss", true)

持续时间不能为负数。