Search code examples
androiddatetimetimechronometer

How to show time in minute:second format, with minutes including the hours?


I want to show the time elapsed from a certain point in my view. I am using the Chronometer class for that.

The issue is, however, that after one hour, it goes to show "1:00:00", but I want it to show 60:00 and so on (like after 80 minutes it should be 80:00 and not 1:20:00)

I have tried using SimpleDateFormat class with "mm:ss" formatting. Sure, it doesn't show the hour, but after an hour it just goes to 00:00 and so on.

Is there a solution for this, such as a custom formatter in Java that I can use?


Solution

  • So this is the solution I came up with after combining @parliament's answer:

    // This is my base time for the chronometer
    baseTime = SystemClock.elapsedRealtime() - (new Date().getTime() - myInitialTimeInMillis);
    Date baseDate = new Date(baseTime);
    chronometer.setOnChronometerTickListener(chronometer1 -> {
            baseTime += 1000;
            baseDate.setTime(baseTime);
            chronometer.setText(getTimeInMinuteSecondFormat(baseDate));
    });
    chronometer.start();
    

    This is my common util method for getting formatted time:

    public static String getTimeInMinuteSecondFormat(Date date) {
        String displayTime = getHourMinuteSecondFormatDate(date);
        String[] splitDisplayTime = displayTime.split(":");
        if (Integer.valueOf(splitDisplayTime[0]) <= 0) {
            return splitDisplayTime[1] + ":" + splitDisplayTime[2];
        } else {
            return (Integer.valueOf(splitDisplayTime[0]) * 60) + Integer.valueOf(splitDisplayTime[1]) + ":" + splitDisplayTime[2];
        }
    }
    

    Works like a charm! Thanks @parliament