如何以秒精度制造秒表?

问题描述 投票:0回答:2

我正在尝试制作秒精度为秒的秒表。我有这段代码每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){}的帮助。

java time datetime-format runnable
2个回答
1
投票

看看是否有帮助。余数未正确计算。

  • 对于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

0
投票

使用标准库

您的计时器不正确。您观察到的延迟来自那里。每次从某个时钟读取时间,而不是增加1/100秒。例如使用System.currentTimeMillis()System.nanoTime()Instant.now()。保持秒表启动时的读数,并减去以获取当前的秒表值。

如果要使用Java 9或更高版本,则下一步,请使用Duration类将时间(以毫秒或纳秒为单位)转换为分钟和秒。如果您尝试进行手动转换,则容易出错且难以阅读(IMHO)。

© www.soinside.com 2019 - 2024. All rights reserved.