Java - Convert Milliseconds to Hours, Minutes, Seconds

The TimeUnit class allows you to easily convert Milliseconds to Hours, Minutes, and Seconds units. Of course, you can get the hours, minutes, and seconds by directly dividing the milliseconds.

Convert Milliseconds to TimeUnit

As shown below, TimeUnit provides methods to convert milliseconds to other units.

long milliseconds = 4000000;
long hours = TimeUnit.MILLISECONDS.toHours(milliseconds);
long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds);
long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds);

System.out.println("hours: " + hours);
System.out.println("minutes: " + minutes);
System.out.println("seconds: " + seconds);

result

hours: 1
minutes: 66
seconds: 4000

In addition to this, TimeUnit also provides APIs to convert various time units to other units, such as:

TimeUnit.SECONDS.toHours()
TimeUnit.SECONDS.toMinutes()
TimeUnit.DAYS.toMinutes()
TimeUnit.NANOSECONDS.toSeconds()

For more information on time units supported by TimeUnit, refer to Oracle - TimeUnit .

Convert by calculation

You can directly convert milliseconds to seconds and convert it to minutes and days.

The code below outputs the same result as using TimeUnit.

long milliseconds = 4000000;
long hours = (milliseconds / 1000) / 60 / 60;
long minutes = (milliseconds / 1000) / 60;
long seconds = (milliseconds / 1000);

System.out.println("hours: " + hours);
System.out.println("minutes: " + minutes);
System.out.println("seconds: " + seconds);

result

hours: 1
minutes: 66
seconds: 4000

Output all units together (ex. 00:00:00)

The above examples simply output the result of converting milliseconds to a specific time unit.

To express as "hours, minutes and seconds", you can use % as in the code below.

long milliseconds = 4000000;
long hours = (milliseconds / 1000) / 60 / 60 % 24;
long minutes = (milliseconds / 1000) / 60 % 60;
long seconds = (milliseconds / 1000) % 60;

System.out.println("hours: " + hours + ", minutes: " + minutes + ", seconds: " + seconds);
System.out.format("%02d:%02d:%02d", hours, minutes, seconds);

The result is the output as we intended. Format can also be used to express in 00:00:00 format.

hours: 1, minutes: 6, seconds: 40
01:06:40

Reference

codechachaCopyright ©2019 codechacha