我有两个 ZonedDateTime
实例:
final ZonedDateTime a = ...;
final ZonedDateTime b = ...;
我想获得这两个值中的最大值。我想避免编写自定义的临时代码。
在 Java 8 中执行此操作的最佳方法是什么?我目前正在这样做:
final ZonedDateTime c = Stream.of(a, b).max(ChronoZonedDateTime::compareTo).get();
有没有更好的方法?
最佳答案
你可以简单地调用isAfter
:
ZonedDateTime max = a.isAfter(b) ? a : b;
或者因为该类实现了Comparable
:
a.compareTo(b);
正如 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));
生成
false - false - true
1
关于java - 如何获得两个 ZonedDateTime 实例中的最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58510990/