我怎样才能得到A时间和B时间之间的差距?

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

我想得到两个视频的时长差距,以毫秒为单位。

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. 为什么 getTime() 的值是负数?因为我没有定义 yy-MM-dd 日期方法?

  2. 我可以使用 Date 方法获取和计算像 HH:mm:ss.SSS 这样的持续时间吗?我不需要年月日等

  3. 我怎样才能正常两个时长的差距?

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

因为日期早于 1970 年 1 月 1 日午夜 GMT。您显然处于 GMT+XX:XX 时区,因此尽管他们在该时区 1970 年之后,但他们不在 GMT。

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

是的,间接的。如果没有日期部分,SimpleDateFormat 假设格林威治标准时间 1970 年 1 月 1 日午夜。

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

Java的原始Date对象不是很有用。 JDK 8 添加 java.time package with more useful classes in it, including Duration.

how can I normal gap of two durations?

这就是您的代码当前正在执行的操作。它以毫秒为单位获取间隔(间隙)。这是一个正数,因为您正在做 A - B,而 A 晚于 B。如果需要,您可以通过 Duration.ofMillis 将该数字变成 Duration

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

...虽然只是为了格式化它不会给你带来太多好处,但我不会立即在 java.time.format 中看到任何格式化 Durations 或 TemporalAmounts 的内容。

java.time.Duration

自 Java 8: 为什么不使用 Duration.between(Temporal startInclusive, Temporal endExclusive)

Duration tempDuration = Duration.between(A1.toInstant(), A2.toInstant());
System.out.println(tempDuration.toMillis());

https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html

The result can be negative if the first date is after the second.

Can also use LocalTime instead of date