Saturday, September 15, 2018

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

Sometimes we need to convert the milliseconds into days or hours or minutes or seconds, so in this post we will see how to convert milliseconds into days, hours, minutes, seconds in Java.

Basically 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.

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

Lets see the below example, it will provide you better idea to convert the milliseconds into days or hours or minutes or seconds.

Formula to convert Milliseconds into Days, Hours, Minutes, Seconds in Java:
seconds = MilliSeconds / 1000;
minutes = seconds / 60;
hours = minutes / 60;
days = hours / 24;

import java.util.concurrent.TimeUnit;

public class MillisToDayHrMinSec {
 public static void main(String[] args) {
  final long milliseconds = 5478965412358l;
  final long day = TimeUnit.MILLISECONDS.toDays(milliseconds);
  final long hours = TimeUnit.MILLISECONDS.toHours(milliseconds)
    - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(milliseconds));
  final long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds)
    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliseconds));
  final long seconds = 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));
  System.out.println("milliseconds :-" + milliseconds);
  System.out.println(String.format("%d Days %d Hours %d Minutes %d Seconds %d Milliseconds", day, hours, minutes, seconds, ms));


Output :
milliseconds :-5478965412358
63413 Days 22 Hours 50 Minutes 12 Seconds 358 Milliseconds

Hope you like this simple example for time conversion, where we are converting milliseconds into days or hours or minutes or seconds. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment