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

Java 如何正确使用ThreeTenABP获取基于UTC的两个日期之间的时间(以毫秒为单位),java,android,java-time,date-difference,threetenbp,Java,Android,Java Time,Date Difference,Threetenbp,我正在使用我刚刚发现的这个库,它应该比Joda time for android要轻,我说,见鬼,让我们使用它吧。但现在,除了这两种方法外,我还在努力在网上找到关于如何使用它的好例子: // ZonedDateTime contains timezone information at the end // For example, 2011-12-03T10:15:30+01:00[Europe/Paris] public static ZonedDateTime getDate(String

我正在使用我刚刚发现的这个库,它应该比Joda time for android要轻,我说,见鬼,让我们使用它吧。但现在,除了这两种方法外,我还在努力在网上找到关于如何使用它的好例子:

// 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");
这张照片是:

我使用的是您的
getDate
方法,因此所需的格式是
ZonedDateTime
(根据ISO 8601修改),例如
2011-12-03T10:15:30+01:00[欧洲/巴黎]
。秒和秒的分数是可选的,方括号中的时区ID也是可选的

顺便说一句,在找到差异之前,您不需要转换为UTC。即使不进行转换,也会得到相同的结果

你也可能得到年、月、日的差异。
Period
类可以提供此功能,但它无法处理一天中的时间,因此首先转换为
LocalDate

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

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

要获得小时、分钟和秒的差异,请使用
Duration
类(我引入了一个新的时间,因为使用
Duration
近6年太不典型了(尽管可能))

区别在于PT13H1M15S


13小时1分15秒。您已经知道的
2011-12-03T10:15:30+01:00[欧洲/巴黎]
中的
T
也将日期部分与时间部分分开,因此您知道在这种情况下
1M
意味着1分钟,而不是1个月。

哇,非常感谢!!非常感谢。如果您不介意告诉我将日期传递给getDate()方法的正确日期格式,是这样的;yyyy-MM-dd'HH:MM:ss?我找到它:“yyyy-MM-dd'HH:MM:ssXXX”顺便说一句,我的朋友,我得到差异后如何转换为UTC?如果我不清楚,很抱歉;我的意思是,如果差异是您所需要的,您根本不需要转换为UTC(也就是说,您可以选择从您的方法中省略
。withZoneSameInstant(ZoneId.of(“UTC”))
))。我正在尝试您的代码,它的显示调用需要api级别26。但我使用的是min级别17
    Period diff = Period.between(zdt1.toLocalDate(), zdt2.toLocalDate());
    System.out.println("Difference is " + diff);
    ZonedDateTime zdt3 = getDate("2017-11-24T18:45:00+01:00[Europe/Copenhagen]");
    Duration diff = Duration.between(zdt2, zdt3);
    System.out.println("Difference is " + diff);