How To Format Milliseconds into Time

5 years ago by in How To, Utilities

We can format a time expressed as milliseconds into MM:SS.SSS using the following function.

public static String formatMillis(long timeInMillis) {
  String sign = "";
  if (timeInMillis < 0) {
    sign = "-";
    timeInMillis = Math.abs(timeInMillis);

  long minutes = timeInMillis / TimeUnit.MINUTES.toMillis(1);
  long seconds = timeInMillis % TimeUnit.MINUTES.toMillis(1) / TimeUnit.SECONDS.toMillis(1);
  long millis = timeInMillis % TimeUnit.SECONDS.toMillis(1);

  final StringBuilder formatted = new StringBuilder(20);
  formatted.append(String.format("%02d", minutes));
  formatted.append(String.format(":%02d", seconds));
  formatted.append(String.format(".%03d", millis));

  return formatted.toString();

This function can be easily modified to cater for the hours as well.

Albert Attard

Albert Attard is a Java passionate and technical lead at a research group. You can find him on . Over the past years Albert worked on various Java projects including traditional server/client applications, modular applications, large data handling applications and concurrent data manipulation applications to name a few. He has a BSc degree from the University of London (Homepage) and an MSc Information Security with the same university. His MSc thesis (Book) received the 2012 award (Website).

Leave a Comment

Time limit is exhausted. Please reload the CAPTCHA.