我们通常可以用 long ms=System.currentTimeMillis(); 来取得以毫秒为单位起始时间和终止时间,它们的时间差除以一千就知道一段Java程序运行了多少秒,但多少秒并不直观,比如900秒你要反应一下,说15分就马上反应过来了。下面提供了计算的函数 和使用示例代码:
public static void main(String[] args) { long startMs=System.currentTimeMillis(); ... // do something
long endMs=System.currentTimeMillis(); System.out.println("Time elapsed:"+ms2DHMS(startMs,endMs)); } /** * change seconds to DayHourMinuteSecond format * * @param startMs * @param endMs * @return */ private static String ms2DHMS(long startMs, long endMs) { String retval = null; long secondCount = (endMs - startMs) / 1000; String ms = (endMs - startMs) % 1000 + "ms"; long days = secondCount / (60 * 60 * 24); long hours = (secondCount % (60 * 60 * 24)) / (60 * 60); long minutes = (secondCount % (60 * 60)) / 60; long seconds = secondCount % 60; if (days > 0) { retval = days + "d" + hours + "h" + minutes + "m" + seconds + "s"; } else if (hours > 0) { retval = hours + "h" + minutes + "m" + seconds + "s"; } else if (minutes > 0) { retval = minutes + "m" + seconds + "s"; } else if(seconds > 0) { retval = seconds + "s"; }else { return ms; } return retval + ms; }
输出示例:
Time elapsed:3m55s872ms
--2020年2月29日--