ofleaf ofleaf - 6 months ago 9
Java Question

How can I get the gap between A time and B time?

I want get the durations gap of two videos contain milliseconds.

A : 01:18:19.92, B : 01:18:19.57

public String calTime(String A, String B) {

String sFormat = "HH:mm:ss.SSS";
SimpleDateFormat dFormat = new SimpleDateFormat(sFormat);

try {

Date A1 = dFormat.parse(A);
Date A2 = dFormat.parse(B);

//A1 = Thu Jan 01 01:18:19 KST 1970
//A1.getTime() = -27700943
//A2 = Thu Jan 01 01:18:19 KST 1970
//A2.getTime() = -27701000

System.out.println(A1.getTime() - A2.getTime());

} catch (ParseException ex) {}

}



  1. Why are the values from
    getTime()
    negative? Cause I didn't define yy-MM-dd the Date method?

  2. Can I get and calculation durations like HH:mm:ss.SSS using Date method? I don't need year, month, day, etc.

  3. how can I normal gap of two durations?


Answer

Why appear minus front of getTime() values? Cause I didn't define yy-MM-dd the Date method?

Because the dates are before Jan 1st 1970 at midnight GMT. You're clearly in a GMT+XX:XX timezone, so although they're after 1970 in that timezone, they aren't in GMT.

Cause I didn't define yy-MM-dd the Date method?

Yes, indirectly. SimpleDateFormat assumes midnight Jan 1st 1970 GMT if there is no date portion.

Can I get and calculation durations like HH:mm:ss.SSS using Date method?

Java's original Date object is not very useful. JDK 8 adds the java.time package with more useful classes in it, including Duration.

how can I normal gap of two durations?

That's what your code is currently doing. It's getting the interval (gap) in milliseconds. It's a positive number because you're doing A - B, and A is later than B. You can turn that number into a Duration via Duration.ofMillis if desired:

long interval = A1.getTime() - A2.getTime();
System.out.println("interval in ms: " + interval);
Duration d = Duration.ofMillis(interval);
System.out.println("duration: " + d);

Live Example

...though just for formatting it doesn't buy you much, I'm not immediately seeing anything in java.time.format that formats Durations or TemporalAmounts.