我想获得JVM的启动时间和正常运行时间。到目前为止,我已经这样做了:
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方法?
答案 0 :(得分:50)
一旦你有时间(以毫秒为单位),你可以使用TimeUnit枚举将其转换为其他时间单位。转换为几天只需要一个电话。
long days = TimeUnit.MILLISECONDS.toDays(milliseconds);
获取小时数将涉及另外一个类似的总小时数,然后计算在减去天数后的数小时内的剩余时间。
答案 1 :(得分:38)
下面的代码会完成您需要的数学运算并构建结果字符串:
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());
答案 2 :(得分:2)
看看Pretty Time。它是一个用于从时间戳(如毫秒)生成人类可读时间字符串的库。
答案 3 :(得分:0)
下面的代码很干净地完成了工作
package com.company;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
final long milliseconds;
Scanner in = new Scanner(System.in);
System.out.println("Enter time in milliseconds: ");
milliseconds = in.nextLong();
final long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds);
final long minute = TimeUnit.MILLISECONDS.toMinutes(milliseconds);
final long hours = TimeUnit.MILLISECONDS.toHours(milliseconds);
final long days = TimeUnit.MILLISECONDS.toDays(milliseconds);
if(milliseconds < 1000){
System.out.println(days +"d:" +hours+"h:" +minute+"m:" +seconds +"s:" +milliseconds +"ms");
}
else{
System.out.println(days +"d:" +hours % 24 +"h:" +minute % 60 +"m:" +seconds % 60 +"s");
}
}
}
样本输出
以毫秒为单位输入时间:12000000
0d:3h:20m:0s