Gilad S
Gilad S

Reputation: 2023

Convert from milliseconds to MM:ss.mmm (Java)

I need to create a method with the following signature:

public String getPrintTime (int t);

t represents time in milliseconds ranging 1-5120000. The output needs to be in the format MM:ss:mmm. For example:

getPrintTime(2342819) == 39:02.819

getPrintTime(23) == 00:00.023

getPrintTime(2340000) == 39:00.000

I have tried in many ways but couldn't get it to work in all of the cases.

Upvotes: 0

Views: 1623

Answers (1)

tobias_k
tobias_k

Reputation: 82899

You can use SimpleDateFormat for this. Note, however, that the correct format string is not MM:ss.mmm but mm:ss.SSS.

SimpleDateFormat sdf = new SimpleDateFormat("mm:ss.SSS");
String formatted = sdf.format(new Date(t));

Alternatively, roll your own with simple division, modulo, and String.format:

int minutes = t /(1000 * 60);
int seconds = t / 1000 % 60;
int millis  = t % 1000;
String formatted = String.format("%02d:%02d.%03d", minutes, seconds, millis);

Upvotes: 4

Related Questions