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


当前回答

如果你不想拖进库,使用Formatter或相关的快捷方式就足够简单了。给定整数秒数s:

  String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));

其他回答

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

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

DurationFormatUtils.formatDuration(millis, "**H:mm:ss**", true);

使用这个func

private static String strDuration(long duration) {
    int ms, s, m, h, d;
    double dec;
    double time = duration * 1.0;

    time = (time / 1000.0);
    dec = time % 1;
    time = time - dec;
    ms = (int)(dec * 1000);

    time = (time / 60.0);
    dec = time % 1;
    time = time - dec;
    s = (int)(dec * 60);

    time = (time / 60.0);
    dec = time % 1;
    time = time - dec;
    m = (int)(dec * 60);

    time = (time / 24.0);
    dec = time % 1;
    time = time - dec;
    h = (int)(dec * 24);
    
    d = (int)time;
    
    return (String.format("%d d - %02d:%02d:%02d.%03d", d, h, m, s, ms));
}

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

E.g.

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

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

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

import android.text.format.DateUtils

例如:DateUtils.formatElapsedTime()

Android date duration elapsedtime