Sunny
Sunny

Reputation: 7604

Java: Converting milliseconds to HH:MM:SS

I have a value in milliseconds which I would like to covert to HH::MM:SS.fff This is just for duration purposes.

I know there is a basic way of doing this:

String.format("%d min, %d sec", 
    TimeUnit.MILLISECONDS.toMinutes(millis),
    TimeUnit.MILLISECONDS.toSeconds(millis) - 
    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);

But is there a better way of doing this? Thanks.

Upvotes: 6

Views: 8814

Answers (2)

Thanakron Tandavas
Thanakron Tandavas

Reputation: 5683

This math will do the trick :

int sec  = (int)(millis/ 1000) % 60 ;
int min  = (int)((millis/ (1000*60)) % 60);
int hr   = (int)((millis/ (1000*60*60)) % 24);

If you want only Minute and Second, Then :

int sec  = (int)(millis/ 1000) % 60 ;
int min  = (int)((millis/ (1000) / 60);

Upvotes: 10

Jon Skeet
Jon Skeet

Reputation: 1499860

It sounds like you want either Duration or Period from Joda Time. For example:

import org.joda.time.*;

public class Test {
    public static void main(String[] args) throws Exception {
        long millis = 12345678L; // Just an example
        PeriodType minutesEtc = PeriodType.time().withHoursRemoved();
        Period period = new Period(millis, minutesEtc);
        String text = String.format("%d min, %d sec",
                                    period.getMinutes(),
                                    period.getSeconds());
        System.out.println(text);
    }
}

(While you can certainly just do the arithmetic by hand, I would personally try to keep it as a Period as far as possible.)

Upvotes: 1

Related Questions