java 排序本地日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32625407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:30:34  来源:igfitidea点击:

Sorting LocalDateTime

javasortingdatetimejodatimejava-time

提问by Abdullah Asendar

How to sort LocalDateTimeobjects?

如何对LocalDateTime对象进行排序?

I tried the following:

我尝试了以下方法:

Comparator<Data> comparator = new Comparator<Data>() {
    @Override
    public int compare(final data o1, final data o2) {
        if (o1.getDate()== null || o2.getDate() == null)
            return 0;
        return o1.getDate().compareTo(o2.getDate());
    }
};

Collections.sort(comments, comparator);

After testing I think it sorts according to the date, but is the time part (HH:MM:SS) ignored?

经过测试,我认为它是根据日期排序的,但是时间部分 (HH:MM:SS) 是否被忽略了?

回答by Adam Michalik

Both JodaTime and JDK 8 LocalDateTimeclasses implement the Comparableinterface, so you can sort them using their natural order. Just do

JodaTime 和 JDK 8LocalDateTime类都实现了该Comparable接口,因此您可以使用它们的自然顺序对它们进行排序。做就是了

Collections.sort(data);

回答by jasper

Check out isAfter()and isBefore(). Click for the Docs. And maybe try to work on your indentation, I was a bit uncertain as to what is inside the if clause. Maybe even try to use curly braces {} even fore one-liners, but that's a matter of personal preference.

查看isAfter()isBefore()。单击以获取文档。也许尝试处理您的缩进,我有点不确定 if 子句中的内容。甚至可以尝试使用花括号 {} 甚至前一行,但这是个人喜好的问题。