我有一个按以下方式计算的变量 currTime:
long currTime = System.currentTimeMillis() - start; //where start is the start time of whatever I'm timing
如何将其转换为字符串以进行显示,例如:
12544 将显示为“00:12.54”
67855 将显示为“01:07.86”
...等等等等...?
我认为最简单的方法是手动完成:
public String elapsedToString(long elapsedTimeMillis) {
long seconds = (elapsedTimeMillis + 500) / 1000; // round
long minutes = seconds / 60;
long hours = minutes / 60;
return String.format("%1$02d:%2$02d:%3$02d",
hours,
minutes % 60,
seconds % 60);
}
哎呀。你想要mm:ss.ss
public String elapsedToString(long elapsedTimeMillis) {
long hundredths = (elapsedTimeMillis + 5) / 10; // round
long seconds = hundredths / 100;
long minutes = seconds / 60;
return String.format("%1$02d:%2$02d.%3$02d",
minutes,
seconds % 60,
hundredths % 100);
}
三位数毫秒的解决方案非常简单:
public String formatDuration(long elapsedTimeMillis) {
SimpleDateFormat df = new java.text.SimpleDateFormat("mm:ss.SSS");
df.setTimeZone(TimeZone.getTimeZone("UTC")); // Epoch is UTC
return df.format(new Date(elapsedTimeMillis));
}
对于两位数毫秒,必须使用 Joda Time 格式化程序,从字符串中删除最后一个数字或寻求手动解决方案。