如何正确使用 ThreeTenABP 获取基于 UTC 的两个日期之间的时间(以毫秒为单位)

How to properly use ThreeTenABP to get the time in milliseconds between two dates based on UTC

我正在使用我刚刚发现的这个库,据说它比 android 的 Joda 时间要轻,我说管它呢,让我们使用它吧。但是现在我正在努力在网络上找到任何关于如何使用它的好例子,除了这两种方法之外:

// ZonedDateTime contains timezone information at the end
// For example, 2011-12-03T10:15:30+01:00[Europe/Paris]
public static ZonedDateTime getDate(String dateString) {
    return ZonedDateTime.parse(dateString).withZoneSameInstant(ZoneId.of("UTC"));
}

public static String formatDate(String format, String dateString) {
    return DateTimeFormatter.ofPattern(format).format(getDate(dateString));
}

那么如何使用这个库获取两个日期之间的差异?

有多种选择,具体取决于您对获得的差异的需求。

最容易找到以某个时间单位测量的差异。使用 ChronoUnit.between。例如:

    ZonedDateTime zdt1 = getDate("2011-12-03T10:15:30+01:00[Europe/Paris]");
    ZonedDateTime zdt2 = getDate("2017-11-23T23:43:45-05:00[America/New_York]");

    long diffYears = ChronoUnit.YEARS.between(zdt1, zdt2);
    System.out.println("Difference is " + diffYears + " years");

    long diffMilliseconds = ChronoUnit.MILLIS.between(zdt1, zdt2);
    System.out.println("Difference is " + diffMilliseconds + " ms");

这会打印:

Difference is 5 years
Difference is 188594895000 ms

我正在使用您的 getDate 方法,因此需要的格式是 ZonedDateTime(从 ISO 8601 修改而来),​​例如 2011-12-03T10:15:30+01:00[Europe/Paris]。秒和秒的小数部分是可选的,方括号中的时区 ID 也是可选的。

顺便说一句,您无需转换为 UTC 即可找到差异。即使您省略了该转换,您也会得到相同的结果。

您还可以得到年、月、日的差异。 Period class 可以给你这个,但它不能处理一天中的时间,所以先转换为 LocalDate

    Period diff = Period.between(zdt1.toLocalDate(), zdt2.toLocalDate());
    System.out.println("Difference is " + diff);

Difference is P5Y11M21D

输出的意思是5年11个月21天。起初语法可能有点奇怪,但很简单。它由 ISO 8601 标准定义。在这种情况下,时区很重要,因为所有时区的日期都不会相同。

要获得小时、分钟和秒的差异,请使用 Duration class(我正在介绍一个新时间,因为使用 Duration 将近 6 年太不典型了(虽然可能))。

    ZonedDateTime zdt3 = getDate("2017-11-24T18:45:00+01:00[Europe/Copenhagen]");
    Duration diff = Duration.between(zdt2, zdt3);
    System.out.println("Difference is " + diff);

Difference is PT13H1M15S

一段13小时1分15秒。您已经从 2011-12-03T10:15:30+01:00[Europe/Paris] 中知道的 T 也将日期部分与时间部分分开,因此您知道在这种情况下 1M 表示 1 分钟,而不是 1 个月。