如何将毫秒转换为小时和天?

如何将毫秒转换为小时和天?

问题描述:

我想获得JVM的启动时间和正常运行时间。到目前为止,我已经这样做了:

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;
}

但是我得到的时间是毫秒。我如何能够在几天和几小时内转换时间。我想以这种格式显示毫秒:3天,8小时,32分钟。是否有可以转换毫秒的内部Java方法?

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?

下面的代码可以完成您需要的数学运算并构建结果字符串:

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());