从DateTime类中查找最新时间戳



我有一个DateTime对象列表,我的任务是比较它们并找到最新的时间戳。DateTime类是从Joda API中使用的。这个问题我已经纠结了一段时间了。我很感激你的帮助。

Collections.max()

DateTimeZone dtz = DateTimeZone.forID("Indian/Comoro");
List<DateTime> dateTimeObjects = Arrays.asList(
new DateTime(2021, 2, 13, 21, 0, dtz),
new DateTime(2021, 2, 13, 22, 0, dtz),
new DateTime(2021, 2, 13, 23, 0, dtz));
DateTime latestDateTime = Collections.max(dateTimeObjects);
System.out.println(latestDateTime);

输出:

2021 - 02年- 13 - t23:00:00.000 + 03:00

Collections.max()抛出NoSuchElementException,如果列表为空。如果列表包含null,则抛出NullPointerException(除非null是唯一的元素,那么它可能被返回)。

当比较来自不同时区的DateTime对象Joda-Time首先比较瞬间,时间点,所以在这种情况下您也会得到最新的。例如:

List<DateTime> dateTimeObjects = Arrays.asList(
new DateTime(2021, 2, 13, 21, 0, DateTimeZone.forID("Asia/Istanbul")),
new DateTime(2021, 2, 13, 22, 0, DateTimeZone.forID("Atlantic/Madeira")),
new DateTime(2021, 2, 13, 23, 0, DateTimeZone.forID("Antarctica/Macquarie")));
DateTime latestDateTime = Collections.max(dateTimeObjects);
System.out.println(latestDateTime);

输出:

2021 - 02 - 13 t22:00:00.000z

我们得到时间22:00到马德拉。您可能想知道,麦格理的时间23:00似乎晚了,但麦格理位于UTC偏移量+11:00,因此时间实际上早了10个小时。DateTime对象是Comparable,按瞬间比较,而不是按时钟小时比较。所以我们得到了最新的时间点。我们总是会的,即使几个时区混在一起。

文档链接:Collections.max()

最新更新