我正在尝试构建一个具有百秒精度的秒表。我有这段代码每 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){} 的帮助。
编辑: 感谢 Ole V.V.和 WJS 的格式答案以及如何解决我遇到的延迟,这是我想出的代码,如果有人需要它,到目前为止它运行良好,也许使用 System.nanoTime() 会给你带来更准确的结果,但是对于我用着还好。
public void start(){
final long timeMillisWhenStarted = System.currentTimeMillis();
if(!isRunning){
isRunning = true;
timer.post(new Runnable() {
@Override
public void run() {
long millisNow = System.currentTimeMillis();
long time = millisNow - timeMillisWhenStarted;
yourtxtView.setText(convertTimeToText(time));
timer.postDelayed(this, 10);
}
});
}
}
private String convertTimeToText(long time){
long hundredths = time / 10;
long sec = hundredths / 100;
long min = sec / 60;
return String.format("%02d:%02d.%02d", min % 60, sec % 60, hundredths % 100);
}
最佳答案
看看这是否有帮助。余数计算不正确。
12340 数百秒
则为123.40 秒
- 所以
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
关于java - 如何制作精度达到百分之一秒的秒表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61256969/