我正在尝试以秒精度制作秒表。我有这段代码每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 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

10-04 21:51