我想将经过的累积秒数转换为小时:分钟:秒。例如
93599 秒到:
25:59:59
我怎样才能做到这一点?(注意:24h 不应该换成 0h)
我想将经过的累积秒数转换为小时:分钟:秒。例如
93599 秒到:
25:59:59
我怎样才能做到这一点?(注意:24h 不应该换成 0h)
模运算符%
在这里很有用。像这样的东西会很好用
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);
}
Java 8 提供了java.time.Duration
用于表示时间量的类。您可以使用Duration#ofSeconds(long)
几秒钟来构建实例。
Duration ellapsed = Duration.ofSeconds(93599);
但是,默认toString
格式看起来像
PT25H59M59S
这不是你想要的。您可以自己进行数学运算(使用各种toMinutes
,toHours
等)将其转换为您想要的格式。这里给出一个例子。
小时 = 93599 / 3600。使用整数算术强制截断。
然后从 93599 中减去 hours * 3600。称之为 foo。或计算 93599 % 3600。
分钟 = foo / 60。使用整数算术。
从 foo 中减去分钟 * 60。打电话给那个酒吧。或计算 foo % 60。
bar 是剩余的秒数。
复制并使用这个类:
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