javadatetimeunit

Convert hh:mm:ss to mmm:ss


I have a Java function that convert seconds to an specific format (hh:mm:ss):

public static String formatChronometer(long seconds) {
    return String.format("%02d:%02d:%02d", TimeUnit.SECONDS.toHours(seconds),
            TimeUnit.SECONDS.toMinutes(seconds) % TimeUnit.HOURS.toMinutes(1),
            TimeUnit.SECONDS.toSeconds(seconds) % TimeUnit.MINUTES.toSeconds(1));
}

My client want to show this chronometer without the "hour" labels. Example:

  1. if 100 hours => 6000:00
  2. if 0 hours and 50 minutes => 50:00
  3. if 1 hour and 12 minutes and 30 seconds => 72:30
  4. if 10 hours and 5 minutes => 600:05
  5. if 0 hours, 0 minutes and 0 seconds => 00:00

How should I change my method?


Solution

  • For flexible minutes number you have to use %d instead of %02d which specify how many digit you want, your solution should look like this :

    return String.format("%d:%02d",
            TimeUnit.SECONDS.toMinutes(seconds),
            TimeUnit.SECONDS.toSeconds(seconds) % TimeUnit.MINUTES.toSeconds(1)
    );
    

    Example

    long[] times = {360000, 3000, 4350, 36300, 0};
    for (long time : times) {
        String result = String.format("%d:%02d",
                TimeUnit.SECONDS.toMinutes(time),
                TimeUnit.SECONDS.toSeconds(time) % TimeUnit.MINUTES.toSeconds(1));
        System.out.println(String.format("%d : %s", time, result));
    }
    

    Outputs

    360000 : 6000:00
    3000   : 50:00
    4350   : 72:30
    36300  : 605:00
    0      : 0:00