检查 "Instant" 的两个实例是否在 Java 8 中的同一日期

Check if two instances of "Instant" are on the same date in Java 8

我有两个来自 java.timeInstant class 实例,例如:

Instant instant1 = Instant.now();
Instant instant2 = Instant.now().plus(5, ChronoUnit.HOURS);

现在我想检查 Instant 的两个实例是否实际上在同一日期(日、月和年匹配)。我想很简单,让我们使用闪亮的新 LocalDate and the universal from 静态方法:

LocalDate localdate1 = LocalDate.from(instant1);
LocalDate localdate2 = LocalDate.from(instant2);

if (localdate1.equals(localdate2)) {
   // All the awesome
}

除了通用的 from 方法不是那么通用并且 Java 在运行时抱怨异常:

java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: 2014-11-04T18:18:12Z of type java.time.Instant

这让我回到第 1 格。

检查 Instant 的两个实例是否具有相同日期(具有相同的日、月和年)的 recommended/fastest 方法是什么?

The Instant class does not work with human units of time, such as years, months, or days. If you want to perform calculations in those units, you can convert an Instant to another class, such as LocalDateTime or ZonedDateTime, by binding the Instant with a time zone. You can then access the value in the desired units.

http://docs.oracle.com/javase/tutorial/datetime/iso/instant.html

因此我建议使用以下代码:

LocalDate ld1 = LocalDateTime.ofInstant(instant1, ZoneId.systemDefault()).toLocalDate();
LocalDate ld2 = LocalDateTime.ofInstant(instant2, ZoneId.systemDefault()).toLocalDate();

if (ld1.isEqual(ld2)) {
    System.out.println("blubb");
}

或者您可以使用

instant.atOffset(ZoneOffset.UTC).toLocalDate();