Search code examples
javadatesimpledateformatuptime

ManagementFactory.getRuntimeMXBean().getUptime() formatting to display day, hours, minutes, and seconds


This is my code to display the uptime of the application:

/**
 * Gets the uptime of the application since the JVM launch
 * @return The uptime in a formatted String (DAYS, MONTHS, MINUTES, SECONDS)
 */
public static String getGameUptime() {
    RuntimeMXBean mxBean = ManagementFactory.getRuntimeMXBean();
    DateFormat dateFormat = new SimpleDateFormat("dd:HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+0"));
    return dateFormat.format(new Date(mxBean.getUptime()));
}

But when the application has only been running for 3 minutes and 50 seconds, it will return a "01:00:03:50". The 01 should be 00 in this case. What is the cause of this? How do I fix this?


Solution

  • Try this

        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        long uptime = mxBean.getUptime();
        String d = uptime / (3600 * 1000 * 24) + ":" + dateFormat.format(uptime);
    

    Note that DateFormat accepts milliseconds as well