Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Converting milliseconds to HH:MM:SS

Tags:

java

time

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.

like image 326
Sunny Avatar asked Mar 15 '13 10:03

Sunny


1 Answers

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);
like image 195
Thanakron Tandavas Avatar answered Sep 24 '22 18:09

Thanakron Tandavas