Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (10.2k points)

I'm confused. After stumbling upon this thread, I tried to figure out how to format a countdown timer that had the format hh:mm:ss.

Here's my attempt -

//hh:mm:ss

String.format("%02d:%02d:%02d", 

    TimeUnit.MILLISECONDS.toHours(millis),

    TimeUnit.MILLISECONDS.toMinutes(millis) - 

    TimeUnit.MINUTES.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),

    TimeUnit.MILLISECONDS.toSeconds(millis) - 

    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));   

So, when I try a value like 3600000ms, I get 01:59:00, which is wrong since it should be 01:00:00. Obviously there's something wrong with my logic, but at the moment, I cannot see what it is!

Can anyone help?

1 Answer

0 votes
by (46k points)

The generic method for this is fairly simple:

public static String convertSecondsToHMmSs(long seconds) {

    long s = seconds % 60;

    long m = (seconds / 60) % 60;

    long h = (seconds / (60 * 60)) % 24;

    return String.format("%d:%02d:%02d", h,m,s);

}

Related questions

Browse Categories

...