2

I have 2 string in java (HH:MM:SS) please take note this is not time, but duration, i used end time - start time to get these values:

Case1:

duration1 = "12:04:45";

duration2 = "13:04:45";

Expected result: duration1 - duration 2 = "-1:00:00" (Note that there is negative)

Case2:

duration1 = "15:13:32";

duration2 = "12:04:45";

Expected result: duration1 - duration 2 = "3:08:47"

How can i do that? My attempt for the Case1 (codes modified from 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
Community
  • 1
  • 1
hades
  • 4,294
  • 9
  • 46
  • 71

3 Answers3

2

With the Java time API you could use a Duration to calculate the duration and format it as you want:

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

If you want to print it as -1:00:00 you will need to tweak the output format. It could look like this:

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;
}
assylias
  • 321,522
  • 82
  • 660
  • 783
2

Using LocalTime or date calculations like some people suggest doesn't work if your period involved more than 24 hours since that doesn't fit in a day.

If you don't have Java 8, you can use JodaTime. I've just checked that this code also works with JodaTime 1.6.2, which is the last version that still works with 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));

Output:

-01:00:00
03:08:47

JodaTime:

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
  • can i use this library for java version "1.4.2" – hades Jan 05 '16 at 13:20
  • For JodaTime 2.0 and higher you need JDK 1.5 or higher. I don't think the Period class is in 1.6.2 (the last version that works with JDK 1.4) but I'll check – Erwin Bolwidt Jan 05 '16 at 13:22
  • @user3172596 I just checked but this works with 1.6.2 as well so you can use it with jdk 1.4.2 – Erwin Bolwidt Jan 05 '16 at 14:07
  • Correct answer, and Joda-Time is always better than using the old troublesome date-time classes. One further suggestion: Use the [standard ISO 8601 format for durations](https://en.wikipedia.org/wiki/ISO_8601#Durations) rather than the Question’s format that is so easily confused with a time-of-day. Joda-Time uses the standard format by default for both parsing and generating a String representation. Format is `PnYnMnDTnHnMnS` where `P` marks beginning and `T` separates the years-months-days portion from hours-minute-seconds. Ex: `PT3H8M47S`. – Basil Bourque Jan 05 '16 at 14:40
  • @Erwin Bolwidt thanks! btw, if duration 1 is 12:03:32, duration is 12:04:39, using duration1- duration2 will get 00:-01:-07, is there any formatting for joda so i can show -00:01:07 ? – hades Jan 06 '16 at 02:33
0

Use Calendar to calculate the time difference.
You can query each field and/or format as a time string as this example shows:

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; 
}
Leet-Falcon
  • 2,107
  • 2
  • 15
  • 23