Java在HH:MM:SS中减去2个持续时间

时间:2016-01-05 12:34:00

标签: java date

我在java中有2个字符串(HH:MM:SS)请注意这是不是时间,但是持续时间,我用了结束时间 - 开始时间来获取这些价值观:

情况1:

duration1 =" 12:04:45&#34 ;;

duration2 =" 13:04:45&#34 ;;

预期结果:duration1 - 持续时间2 =" -1:00:00" (注意有负面)

情况2:

duration1 =" 15:13:32&#34 ;;

duration2 =" 12:04:45&#34 ;;

预期结果:duration1 - 持续时间2 =" 3:08:47"

我该怎么做?我对Case1的尝试(代码从Java add dates of format dd:HH:mm:ss修改):

SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");    

String s1 = "12:04:45";
String s2 = "13:04:45";

Date d1 = format.parse(s1);
Date d2 = format.parse(s2);

int sec = d1.getSeconds() - d2.getSeconds();
int min = d1.getMinutes() - d2.getMinutes();
int hr = d1.getHours() - d2.getHours();

Time sum = new Time(hr, min, sec);
System.out.println(sum);  // Output: 23:00:00   which is wrong

3 个答案:

答案 0 :(得分:2)

使用LocalTime或日期计算,就像有些人建议的那样,如果你的时间超过24小时,那么这段时间不适用。

如果您没有Java 8,则可以使用JodaTime。我刚检查过这段代码也适用于JodaTime 1.6.2,这是最后一个仍然适用于JDK 1.4.2的版本。

PeriodFormatter formatter = new PeriodFormatterBuilder()
        .printZeroAlways().minimumPrintedDigits(2)
        .appendHours().appendSuffix(":").appendMinutes().appendSuffix(":").appendSeconds()
        .toFormatter();
Period period1 = formatter.parsePeriod("12:04:45");
Period period2 = formatter.parsePeriod("13:04:45");
Period difference1 = period1.minus(period2).normalizedStandard();
System.out.println(formatter.print(difference1));

Period period3 = formatter.parsePeriod("15:13:32");
Period period4 = formatter.parsePeriod("12:04:45");
Period difference2 = period3.minus(period4).normalizedStandard();
System.out.println(formatter.print(difference2));

输出:

-01:00:00
03:08:47

JodaTime:

答案 1 :(得分:1)

使用Java time API,您可以使用Duration计算持续时间并根据需要对其进行格式化:

String s1 = "12:04:45";
String s2 = "13:04:45";
LocalTime t1 = LocalTime.parse(s1);
LocalTime t2 = LocalTime.parse(s2);

Duration d = Duration.between(t2, t1);
System.out.println(d); //PT-1H

如果要将其打印为-1:00:00,则需要调整输出格式。它看起来像这样:

private static String toHHMMSS(Duration d) {
  long hours = d.toHours();
  int minutes = (int) (d.toMinutes() % 60);
  int secs = (int) (d.getSeconds() % 60);

  return hours + ":" + minutes + ":" + secs;
}

答案 2 :(得分:0)

使用Calendar计算时差 您可以将每个字段和/或格式查询为时间字符串,如此示例所示:

private Calendar getTimeDiffDate(Date d1, Date d2) {
    Calendar c = Calendar.getInstance();
    c.setTime(new Date(d1.getTime()-d2.getTime()));
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); 

    // Format as a time string:
    String formattedTime = formatter.format(c.getTime());
    System.out.println("formattedTime: "+formattedTime);

    // Query by each field:
    System.out.println("Hours: "+c.get(Calendar.HOUR));
    System.out.println("Minutes: "+c.get(Calendar.MINUTE));
    System.out.println("Seconds: "+c.get(Calendar.SECOND));
    return c; 
}