Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert milliseconds into hours and days?

Tags:

java

I want to get the JVM start time and uptime. So far I have done this:

public long getjvmstarttime(){
    final long uptime = ManagementFactory.getRuntimeMXBean().getStartTime();
    return uptime;
}

public long getjvmuptime(){
    final long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
    return uptime;
}

But I get the time in milliseconds. How I can convert the time in days and hours. I want to display the milliseconds in this format: 3 days, 8 hours, 32 minutes. Is there amy internal Java method that can convert the milliseconds?

like image 990
user1285928 Avatar asked Aug 25 '12 20:08

user1285928


People also ask

How do you convert milliseconds to days?

How to Convert Milliseconds to Days. To convert a millisecond measurement to a day measurement, divide the time by the conversion ratio. The time in days is equal to the milliseconds divided by 86,400,000.

How do you divide milliseconds into hours?

To convert milliseconds to hours, minutes, seconds: Divide the milliseconds by 1000 to get the seconds. Divide the seconds by 60 to get the minutes. Divide the minutes by 60 to get the hours.

How do you convert milliseconds to hours in Excel?

So all you need to do is divide the data you have in milliseconds by 86,400,000. Format the result as [h]:mm:ss and you are done. Note that if the value is more than 86,400,000, then you have deal with that, by adjusting the hours. Was this reply helpful?


2 Answers

Once you have the time in milliseconds you can use the TimeUnit enum to convert it to other time units. Converting to days will just require one call.

long days = TimeUnit.MILLISECONDS.toDays(milliseconds);

Getting the hours will involve another similar call for the total hours, then computing the left over hours after the days are subtracted out.

like image 71
Bill the Lizard Avatar answered Sep 28 '22 06:09

Bill the Lizard


The code below does the math you need and builds the resulting string:

private static final int SECOND = 1000;
private static final int MINUTE = 60 * SECOND;
private static final int HOUR = 60 * MINUTE;
private static final int DAY = 24 * HOUR;

// TODO: this is the value in ms
long ms = 10304004543l;
StringBuffer text = new StringBuffer("");
if (ms > DAY) {
  text.append(ms / DAY).append(" days ");
  ms %= DAY;
}
if (ms > HOUR) {
  text.append(ms / HOUR).append(" hours ");
  ms %= HOUR;
}
if (ms > MINUTE) {
  text.append(ms / MINUTE).append(" minutes ");
  ms %= MINUTE;
}
if (ms > SECOND) {
  text.append(ms / SECOND).append(" seconds ");
  ms %= SECOND;
}
text.append(ms + " ms");
System.out.println(text.toString());
like image 25
Dan D. Avatar answered Sep 28 '22 07:09

Dan D.