How to Convert Milliseconds Time into Formatted String (HH:MM:SS) in Java

Nitish Kumar Singh

Nov 12, 2023 . 3 min read

Hello Developers! in this blog post, we will learn how to convert milliseconds time into formatted String in Java. For example 6548000 milliseconds into 1:49:08, so we can show it as duration to user.

When do we need to do this?

For example when we developing a Video or Audio Player or any application where need to show time or duration of video or audio then we need to do this because when we extract duration of video or audio files then generally it extracted in milliseconds. So we need to convert it in String format like in HH:MM:SS format or in x Hours y Minutes z Seconds and show it to users.  

So let's start coding, To do this we use two Java operators: division(/) and modulus(%) to calculate Hours, Minutes and Seconds, and StringBuilder and Formatter to formats it in HH:MM:SS format. 

So below is a Java method that take time in milliseconds and return time in HH:MM:SS formatted String.

private String getTimeInHhMmSsString (int timeMs) {
    int totalSeconds = timeMs / 1000;

    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;

    StringBuilder mFormatBuilder = new StringBuilder();
    Formatter mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

    mFormatBuilder.setLength(0);
    if (hours > 0) {
        return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
    } else {
        return mFormatter.format("%02d:%02d", minutes, seconds).toString();
    }
}

Explanation Points:-

  • modulus(%) operator: This operator gives remainder when one integer divided by other. So totalSeconds % 60 gives seconds as remainder because hours and minutes are multiple of 60, (totalSeconds / 60) % 60 gives minutes as remainder (because let totalSeconds = 120 then 120/60 = 2 and 2 % 60 = 2) and totalSeconds / 3600 gives hours because hours is an int variable.
  • StringBuilder: This class use to build string by appending multiple strings by it's append() method.
  • Formatter: This class use to formats string by using a format specifier (string), arguments  according to specifier and a Locale. In the above code specifier are "%d:%02d:%02d" and "%d:%02d" and arguments are hours, minutes, seconds. Here %d means formats the integer (d mean decimal or integer) and %02d means - format the integer with 2 digits and padding is zero like if argument is 4 then formatted result is 04.

And below is a Java method that take time in milliseconds and return time in hours, minutes, seconds formatted String.

private String getTimeInHoursMinSec(int timeMs) {
    int totalSeconds = timeMs / 1000;

    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;

    if (hours > 0) {
        return hours>1?hours+" hours":" hour" + minutes>1?minutes+" minutes":" minute" + seconds>1?seconds+" seconds":" second";
    } else {
        return minutes>1?minutes+" minutes":" minute" + seconds>1?seconds+" seconds":" second";
    }
}

In the above code, I use Java Ternary Operator(?). Syntax of ternary operator is condition ? value on true : value on false , like in above code if hours greater than 1 then " hours" else " hour" used as value in string concatenation.

Alright, I hope you enjoyed this blog post and learned how to convert milliseconds time into formatted string.

Published on Nov 12, 2023
Comments (undefined)

Read More

How to Change Brightness of Only One Activity in Android Using Java

Hello Developers! In this blog post, we will learn how to change the brightness of only one activity, not for the overall application or the entire phone brightness. For example, if the user drags on the screen, changes the progress of the seek bar, or clicks on buttons, then the brightness of the activity should change. This is a feature commonly seen in Video-Player Apps.

Nov 13, 2023

How to Control Volume using Android SeekBar in Java

Hello Developers! In this blog post, we will learn how to change volume using SeekBar in Android using Java. Basically we increase or decrease system volume of phone when progress of SeekBar chnages and show a TextView for volume level.

Nov 15, 2023

How to Remove All Child Elements at Once in JavaScript

Hello, developers! In this blog post, we will learn how to remove all child elements at once from an HTML element using JavaScript. Removing all children at once is a little problematic task on the web because the web does not have any method like removeAll() that removes all children.

Nov 17, 2023

How to Listen to URL Changes in Next.js for a Route or Overall App

Hello Developers, In this blog post, we will see how to listen to URL changes at the route level or application level in a Next.js app. We will create a listener to listen for URL changes in both App Router and Pages Router.

Nov 23, 2023

How to Get Absolute Paths of Internal and External Storages in Android Development

To get paths, we use the ContextCompat.getExternalFilesDirs method. This method returns paths to the files directory (application-specific) on all available external storage devices. The returned paths are not exactly what we want, but we can modify them to suit our needs.

Nov 24, 2023

How to List All Videos in Android App Development using Java

Hello Developers! In this blog post, we will learn how to list or extract all video files with information from Internal (Phone) and External (SD Card) storages in Android app development using Java. For example, if we are developing a Video Player app, we need to show all videos.

Nov 25, 2023