已经 3 岁了,但没有人正确回复,我会回复
public String format(long millis) {
long allSeconds = millis / 1000;
int allMinutes;
byte seconds, minutes, hours;
if (allSeconds >= 60) {
allMinutes = (int) (allSeconds / 60);
seconds = (byte) (allSeconds % 60);
if (allMinutes >= 60) {
hours = (byte) (allMinutes / 60);
minutes = (byte) (allMinutes % 60);
return String.format(Locale.US, "%d:%d:" + formatSeconds(seconds), hours, minutes, seconds);
} else
return String.format(Locale.US, "%d:" + formatSeconds(seconds), allMinutes, seconds);
} else
return String.format(Locale.US, "0:" + formatSeconds((byte) allSeconds), allSeconds);
}
public String formatSeconds(byte seconds) {
String secondsFormatted;
if (seconds < 10) secondsFormatted = "0%d";
else secondsFormatted = "%d";
return secondsFormatted;
}
millis / 1000 将毫秒转换为秒。示例:
allSeconds = 68950 / 1000 = 68 seconds
如果 allSeconds 大于 60,我们会将分钟与秒分开,然后我们将 allSeconds = 68 转换为分钟,使用:
minutes = allSeconds / 60 = 1 left 8
剩下的数字是秒
seconds = allSeconds % 60 = 8
formatSeconds(byte seconds) 方法在秒数小于 10 时加零。
所以最后会是:1:08
为什么是字节? Long 的性能很差,那么最好使用字节来进行更长的操作。