我正在尝试制作秒精度为秒的秒表。我有这段代码每10毫秒运行一次,但是我无法将其转换为0(min):0(sec):00格式。
timer.post(new Runnable() {
@Override
public void run() {
time += 1;
txtView.setText(convertTimeToText(time));
timer.postDelayed(this, 10);
}
});
private String convertTimeToText(int time) {
String convertedTime = time / 6000 + ":" + (time / 100) % 60
+ ":" + (time / 10) % 10 + time % 10;
return convertedTime;
}
我需要有关格式化时间的convertTimeToText(int time){}的帮助。
看看是否有帮助。余数未正确计算。
12340 hundreds
秒,等于123.40 seconds
12340 / 6000
= 2
分钟12340 % 6000
得到的是340
340 /100
= 3
秒340 % 100
= 40
百分之一public static void main(String[] args) {
// n = 16 mins 4 seconds and 99 hundredths
int n = (16 * 6000) + (4 * 100) + 99;
System.out.println(convertTimeToText(n));
}
private static String convertTimeToText(int time) {
int mins = time / 6000;
time %= 6000; // get remaining hundredths
int seconds = time / 100;
int hundredths = time %= 100; // get remaining hundredths
// format the time. The leading 0's mean to pad single
// digits on the left with 0. The 2 is a field width
return String.format("%02d:%02d:%02d", mins, seconds,
hundredths);
}
此打印
16:04:99
您的计时器不正确。您观察到的延迟来自那里。每次从某个时钟读取时间,而不是增加1/100秒。例如使用System.currentTimeMillis()
,System.nanoTime()
或Instant.now()
。保持秒表启动时的读数,并减去以获取当前的秒表值。
如果要使用Java 9或更高版本,则下一步,请使用Duration
类将时间(以毫秒或纳秒为单位)转换为分钟和秒。如果您尝试进行手动转换,则容易出错且难以阅读(IMHO)。