java - 如何制作精度达到百分之一秒的秒表?

标签 java time datetime-format runnable

我正在尝试构建一个具有百秒精度的秒表。我有这段代码每 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/

相关文章:

java - 运行 JavaCpp 示例时出现 UnsatisfiedLinkException (LegacyLibrary)

java - Java中使用Bit Shift运算将十进制转换为十六进制

java - 如何使用 simple-slack-api 读取 channel 消息?

mysql - 格式化 Excel,列以获得 hh :mm:ss when they are listed that way 的总和

c++ - 自1/1/0000年以来,哪些C++函数支持的时间以微秒为单位?

sql-server - 将 TSQL 中的字符串处理为带时区的日期时间

c# - DateAdd 和 DatePart 从 VB6 到 C#

Java 验证仅针对字符串值集添加约束

java - 时间选择器 ontimeset 错误

c# - 浏览器之间的不同时间格式