0

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Gilad S
  • 1,753
  • 1
  • 13
  • 14
  • Take a look at DateFormat class: http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html – aga Oct 27 '14 at 14:04
  • That argument needs to be a `long` rather than an `int`. – Basil Bourque Oct 27 '14 at 15:22
  • possible duplicate of [how to convert milliseconds to date format in android?](http://stackoverflow.com/questions/7953725/how-to-convert-milliseconds-to-date-format-in-android) – Basil Bourque Oct 27 '14 at 15:25

1 Answers1

4

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);
tobias_k
  • 81,265
  • 12
  • 120
  • 179