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


当前回答

查看所有这些计算,大多数单位(小时、分钟等)都有一个. tofoopart()方便方法,这可能是有帮助的。

E.g.

Duration.ofMinutes(110L).toMinutesPart() == 50

读:到父单位(小时)的下一个值的分钟数。

其他回答

这个答案只使用Duration方法,适用于Java 8:

public static String format(Duration d) {
    long days = d.toDays();
    d = d.minusDays(days);
    long hours = d.toHours();
    d = d.minusHours(hours);
    long minutes = d.toMinutes();
    d = d.minusMinutes(minutes);
    long seconds = d.getSeconds() ;
    return 
            (days ==  0?"":days+" days,")+ 
            (hours == 0?"":hours+" hours,")+ 
            (minutes ==  0?"":minutes+" minutes,")+ 
            (seconds == 0?"":seconds+" seconds,");
}

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

如果你使用的是8年以前的Java版本…你可以使用Joda Time和PeriodFormatter。如果你真的有一个持续时间(即一个经过的时间量,没有参考日历系统),那么你可能应该使用持续时间的大部分-然后你可以调用toPeriod(指定任何你想要反映的PeriodType是否25小时变成1天或1小时,等等)来获得一个你可以格式化的周期。

如果您使用的是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;
}

用这种方式格式化是相当简单的,尽管手工操作很烦人。一般来说,解析它就变得更难了……当然,如果您愿意,您仍然可以在Java 8中使用Joda Time。

那么下面的函数呢 + 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 );
    }
}

我不确定这是你想要的,但检查这个Android helper类

import android.text.format.DateUtils

例如:DateUtils.formatElapsedTime()

Android date duration elapsedtime