# Format Milliseconds Duration to Hours, Minutes and Seconds

Learn to convert a given duration in milliseconds to hours, minutes and seconds; and format to `HH:mm:ss` or any other custom pattern.

## 1. Using Duration APIs

If we know the arithmetic formulas to calculate the hours, minutes or seconds from a given amount of milliseconds then we can use the Duration class methods and apply those calculations ourselves.

Duration class models a quantity or amount of time in terms of seconds and nanoseconds. It provides methods for other duration-based time units such as `toHours()`, `toMinutes`() and `getSeconds()`. We can use these methods to get time in the specific unit and get the modulo to extract the exact amount.

``````long millis = 54321000;

Duration duration = Duration.ofMillis(millis);

long h = duration.toHours();
long m = duration.toMinutes() % 60;
long s = duration.getSeconds() % 60;

String timeInHms = String.format("%02d:%02d:%02d", h, m, s);

System.out.println(timeInHms);	//15:05:21``````

## 2. Apache Common’s DurationFormatUtils

The DurationFormatUtils class provides formatting utilities and constants. Its formatDuration(durationMillis, format) method can be used to format the specified duration in a specified format.

It takes an optional third parameter `padWithZeros` that specifies whether to pad the left-hand side of numbers with 0’s. For example, if we want to write ‘5’ to ’05’ then we should pass the third argument as `true`.

``````long millis = 54321000;

String timeInHms = DurationFormatUtils
.formatDuration(millis, "HH:mm:ss", true);

System.out.println(timeInHms);	//15:05:21

timeInHms = DurationFormatUtils
.formatDuration(millis, "HH:mm:ss", false);

System.out.println(timeInHms);	//15:5:21``````

To use this class, include the latest version of commons-lang from Maven repository.

``````<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>``````

## 3. Conclusion

In this short Java tutorial, we learned to convert a given duration in milliseconds to a formatted string containing hours, minutes and seconds. This information can be useful in printing the logs for long-running jobs where jobs may be running for hours.

Happy Learning !!

Sourcecode on Github

Subscribe
Notify of
Inline Feedbacks

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.