运行以下代码:

private static String formatDuration(final long duration) {
    final long hh = duration / 1000 / 3600;
    final long mm = duration / 1000 % 3600 / 60;
    final long ss = duration / 1000 % 3600 % 60;
    return hh + "h" + ":" + mm + "m" + ":" + ss + "s";
}


private static void printDuartion() throws ParseException{
    SimpleDateFormat PARSE_FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    long dayFrom = PARSE_FORMAT.parse("11/02/2014 00:00:00").getTime();
    long dayTo = PARSE_FORMAT.parse("11/03/2014 23:59:59").getTime();
    System.out.println(formatDuration(dayTo-dayFrom));
}


我有一个输出:
48h:59m:59s

但实际上应该是:
47h:59m:59s

请帮助我找出错误所在。

最佳答案

您的代码正确,我也得到47h:59m:59s。演示:http://ideone.com/fxZKba

我只能想象您所处的时区受Daylight saving time的影响。在以下示例中,类似于“大西洋/百慕大”:

   private static void printDuration() throws Exception {
      SimpleDateFormat PARSE_FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
      PARSE_FORMAT.setTimeZone(TimeZone.getTimeZone("Atlantic/Bermuda"));
      long dayFrom = PARSE_FORMAT.parse("11/02/2014 00:00:00").getTime();
      long dayTo = PARSE_FORMAT.parse("11/03/2014 23:59:59").getTime();
      System.out.println(formatDuration(dayTo - dayFrom));
   }


在这种情况下,我得到48h:59m:59s演示:http://ideone.com/jQ7sX2

关于java - 格式化持续时间问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26753648/

10-10 19:50