Hirak Chhatbar
Hirak Chhatbar

Reputation: 3181

Converting seconds to hours, minutes and seconds

I want to use count up timer in android for long hours...

Currently, I am using this code, but after some hours, say after 10 hours, the format goes like 10 : 650 :56 (hh:mm:ss)... for lesser time, it works perfectly...

 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);

    }

};

Upvotes: 0

Views: 2841

Answers (2)

Adrian Cid Almaguer
Adrian Cid Almaguer

Reputation: 7791

Use this function:

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;
}

You can found other solution in:

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

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93561

Your code for minutes is almost right, but you have to modulus it by 60 just like you do for seconds. Otherwise your value is going to still include all the hours.

Upvotes: 2

Related Questions