如何获得两个 ZonedDateTime 实例的最大值?

tha*_*sme 5 java comparator date-comparison java-stream zoneddatetime

我有两个ZonedDateTime实例:

final ZonedDateTime a = ...;
final ZonedDateTime b = ...;
Run Code Online (Sandbox Code Playgroud)

我想获得这两个值中的最大值。我想避免编写自定义的临时代码。

在 Java 8 中执行此操作的最佳方法是什么?我目前正在这样做:

final ZonedDateTime c = Stream.of(a, b).max(ChronoZonedDateTime::compareTo).get();
Run Code Online (Sandbox Code Playgroud)

有更好的方法吗?

Dea*_*ool 9

ZonedDateTime实现Comparable接口,因此您可以简单使用Collections.max

Collections.max(Arrays.asList(a,b));
Run Code Online (Sandbox Code Playgroud)

  • 这也是 Guava 的建议。例如,请参阅 https://guava.dev/releases/23.0/api/docs/com/google/common/collect/Ordering.html#max-EE-。 (3认同)

Joa*_*son 5

您可以简单地调用isAfter

ZonedDateTime max = a.isAfter(b) ? a : b;
Run Code Online (Sandbox Code Playgroud)

或者因为类实现 Comparable

a.compareTo(b);
Run Code Online (Sandbox Code Playgroud)

正如 OleV.V. 指出的那样 在评论中,这是两种比较时间的方法之间的差异。所以他们可能会为相同的值产生不同的结果

DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
ZonedDateTime time1 = ZonedDateTime.from(formatter.parse("2019-10-31T02:00+01:00"));
ZonedDateTime time2 = ZonedDateTime.from(formatter.parse("2019-10-31T01:00Z"));

System.out.println(time1.isAfter(time2) + " - " + time1.isBefore(time1) + " - " + time1.isEqual(time2));
System.out.println(time1.compareTo(time2));
Run Code Online (Sandbox Code Playgroud)

生成

假 - 假 - 真
1