-2

我想将经过的累积秒数转换为小时:分钟:秒。例如

93599 秒到:

25:59:59

我怎样才能做到这一点?(注意:24h 不应该换成 0h)

4

4 回答 4

3

模运算符%在这里很有用。像这样的东西会很好用

public static void convertTime(int seconds) {
    int secs = seconds % 60;
    int mins = (seconds / 60) % 60;
    int hours = (seconds / 60) / 60;
    System.out.printf("%d:%d:%d", hours, mins, secs);
}
于 2015-07-14T16:08:20.270 回答
1

Java 8 提供了java.time.Duration用于表示时间量的类。您可以使用Duration#ofSeconds(long)几秒钟来构建实例。

Duration ellapsed = Duration.ofSeconds(93599);

但是,默认toString格式看起来像

PT25H59M59S

这不是你想要的。您可以自己进行数学运算(使用各种toMinutes,toHours等)将其转换为您想要的格式。这里给出一个例子。

于 2015-07-14T15:59:22.103 回答
0

小时 = 93599 / 3600。使用整数算术强制截断。

然后从 93599 中减去 hours * 3600。称之为 foo。或计算 93599 % 3600。

分钟 = foo / 60。使用整数算术。

从 foo 中减去分钟 * 60。打电话给那个酒吧。或计算 foo % 60。

bar 是剩余的秒数。

于 2015-07-14T15:54:44.373 回答
-4

复制并使用这个类:

public class AccumulatedTimeFormat extends Format {

@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    Long totalSeconds;

    if(obj instanceof Byte) {
        totalSeconds=((Byte)obj).longValue();
    } else if(obj instanceof Short) {
        totalSeconds=((Short)obj).longValue();
    } else if(obj instanceof Integer) {
        totalSeconds=((Integer)obj).longValue();
    } else if(obj instanceof Long) {
        totalSeconds=((Long)obj);
    } else {
        throw new IllegalArgumentException("Cannot format given Object as an accumulated-time String!");
    }

    long ss = Math.abs(totalSeconds) % 60;
    long mm = (Math.abs(totalSeconds) / 60) % 60;
    long h = (Math.abs(totalSeconds) / 60) / 60;

    if(totalSeconds<0) {
        toAppendTo.append('-');
    }
    toAppendTo.append(String.format("%d:%02d:%02d", h, mm, ss));

    return toAppendTo;
}

@Override
public Object parseObject(String source, ParsePosition pos) {
    //TODO Implement if needed!
    return null;
}

}

像这样:

System.out.println((new AccumulatedTimeFormat()).format(93599));

哪个打印:

25:59:59
于 2015-07-14T15:54:37.313 回答