How to convert milliseconds into hours and days?

后端 未结 3 1934
执笔经年
执笔经年 2020-12-23 15:37

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

public long getjvmstarttime(){
    final long uptime = ManagementFactory.getRuntimeMXBe         


        
相关标签:
3条回答
  • 2020-12-23 15:56

    Take a look at Pretty Time. It's a library for generating human reabable time strings from timestamps like milliseconds.

    0 讨论(0)
  • 2020-12-23 16:05

    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.

    0 讨论(0)
  • 2020-12-23 16:07

    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());
    
    0 讨论(0)
提交回复
热议问题