(Java) Convert milliseconds to minutes and seconds (mm:ss)

For a nice string representation, using the TimeUnit lib:

String.format("%02d:%02d",
     TimeUnit.MILLISECONDS.toMinutes(milliSeconds),
     TimeUnit.MILLISECONDS.toSeconds(milliSeconds) -
     TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliSeconds)));

or simply do the math:

int minutes = (int) (milliSeconds/ 1000)  / 60; 
int seconds = (int) (milliSeconds/ 1000) % 60;

and back to miliseconds again:

long milliSeconds= ((minutes * 60) + seconds) * 1000; 

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *