Convert Milliseconds into Days, Hours, Minutes, Seconds in Java


This example shows you hot to convert milliseconds into days, hours, minutes, seconds in Java. Sometimes we need to convert the milliseconds into days or hours or minutes or seconds.

Typically when you want to check the exact time taken to execute a program then you may need to calculate the time. So in this case you get the start time in milliseconds and end time in milliseconds and you want to check how much time that program took to execute. Therefore you would like to convert the milliseconds into minutes and seconds to make it more readable format because millisecond unit may not be so understandable quickly.

You may also like to read Convert Milliseconds into Years, Months, Weeks, Days, Hours, Minutes, Seconds in Java


Java 1.8

Example with Source Code

The following Java source code will give you the exact thing what you are looking for.

We are not using any modulo (%) or division (/) operators to convert milliseconds into days, hours, minutes, seconds but using Java’s built-in functions to make it happen.

In the below source code we first find out the no of days then hours, then minutes and so on. If we do not find any integer value for any unit of time then it gives 0.

package com.roytuts.time;
import java.util.concurrent.TimeUnit;
public class MillisToDayHrMinSec {
	public static void main(String[] args) {
		final long milliseconds = 5478965412358l;
		final long dy = TimeUnit.MILLISECONDS.toDays(milliseconds);
		final long hr = TimeUnit.MILLISECONDS.toHours(milliseconds)
				- TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(milliseconds));
		final long min = TimeUnit.MILLISECONDS.toMinutes(milliseconds)
				- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliseconds));
		final long sec = TimeUnit.MILLISECONDS.toSeconds(milliseconds)
				- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds));
		final long ms = TimeUnit.MILLISECONDS.toMillis(milliseconds)
				- TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(milliseconds));
				.println(String.format("%d Days %d Hours %d Minutes %d Seconds %d Milliseconds", dy, hr, min, sec, ms));

Testing the Program

When you run the above program you will see below output in the console:


63413 Days 22 Hours 50 Minutes 12 Seconds 358 Milliseconds

That’s all. Hope you got idea how to convert milliseconds into days, hours, minutes, seconds. If you want you may also calculate other units like months, years etc.

Source Code

download source code

Thanks for reading.

Leave a Comment