将秒转换为小时,分钟和秒

时间:2015-03-29 05:13:34

标签: java android string time timer

我想长时间在android中使用count up计时器......

目前,我正在使用这段代码,但过了几个小时后,比如10小时后,格式就像10:650:56(hh:mm:ss)......在较短的时间内,它完美运行......

 private Runnable updateTimerMethod = new Runnable() {

    public void run() {
        timeInMillies = SystemClock.uptimeMillis() - startTime;

        finalTime = timeSwap + timeInMillies;

        int seconds = (int) (finalTime / 1000);
        int minutes = seconds / 60;
        int hours = minutes / 60;
        seconds = seconds % 60;
        int milliseconds = (int) (finalTime % 1000);

        String timer = ("" + String.format("%02d", hours) + " :  "
                + String.format("%02d", minutes) + " : "
                + String.format("%02d", seconds));

        myHandler.postDelayed(this, 0);

        sendLocalBroadcast(timer);

    }

};

2 个答案:

答案 0 :(得分:2)

您的分钟代码几乎是正确的,但您必须将其模数减少60,就像几秒钟一样。否则你的价值仍将包括所有时间。

答案 1 :(得分:0)

使用此功能:

private static String timeConversion(int totalSeconds) {

    final int MINUTES_IN_AN_HOUR = 60;
    final int SECONDS_IN_A_MINUTE = 60;

    int seconds = totalSeconds % SECONDS_IN_A_MINUTE;
    int totalMinutes = totalSeconds / SECONDS_IN_A_MINUTE;
    int minutes = totalMinutes % MINUTES_IN_AN_HOUR;
    int hours = totalMinutes / MINUTES_IN_AN_HOUR;

    return hours + " : " + minutes + " : " + seconds;
}

您可以在以下网址找到其他解决方案:

  

https://codereview.stackexchange.com/q/62713/69166