Search code examples
javasortingdatetimejodatimejava-time

Sorting LocalDateTime


How to sort LocalDateTime objects?

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?


Solution

  • Both JodaTime and JDK 8 LocalDateTime classes implement the Comparable interface, so you can sort them using their natural order. Just do

    Collections.sort(data);