Joda DateTime 数组按日期时间排序数组

Joda DateTime array sort array by date time

我有一个这样的 Joda DateTimes 数组列表:

List <DateTime> nextRemindersArray = new ArrayList<DateTime>();
nextRemindersArray.add(reminderOneDateTime);
nextRemindersArray.add(reminderTwoDateTime);
nextRemindersArray.add(reminderThreeDateTime);

我正在尝试按升序对日期进行排序,但我遇到了问题:

我用谷歌搜索并找到了这个页面:

https://cmsoftwaretech.wordpress.com/2015/07/19/sort-date-with-timezone-format-using-joda-time/

我这样试过:

nextRemindersArray.sort(nextRemindersArray);

但它给了我错误:

Error:(1496, 37) error: incompatible types: List<DateTime> cannot be converted to Comparator<? super DateTime>

然后我这样尝试:

DateTimeComparator dateTimeComparator = DateTimeComparator.getInstance();
nextRemindersArray.sort(nextRemindersArray, dateTimeComparator);

还有这样的:

nextRemindersArray.sort(nextRemindersArray, new DateTimeComparator());

但都有错误。

我尝试了 Joda 时间手册,但没有太大帮助。如何对数组进行排序?

在此先感谢您的帮助

您要找的是:

nextRemindersArray.sort(DateTimeComparator.getInstance());

但是因为 DateTime 已经实现了 Comparable,你真的不需要比较器,你可以简单地使用:

nextRemindersArray.sort(null); //uses natural sorting
//or probably more readable
Collections.sort(nextRemindersArray);

请注意,快速查看 the documentation of List::sort 会告诉您该方法只需要一个参数,并且它必须是一个比较器(而不是像您的问题中那样的两个参数)。

假设我们有一个带有此方法 getCreatedDate() 的 SomeClass,它 returns 一个 DateTime joda 对象。 对于 List 你可以有一个简单的比较器:

private Comparator<Listing> byCreatedDate = Comparator.comparing(SomeClass::getCreatedDate);

然后在你的代码中你可以调用:

 ...
 listings.sort(byCreatedDate);
 return listings;
 ...

没测试过,不过……思路应该没问题。

在 Kotlin 中你会调用 listing.sortedBy { it.createdDate }