Sorting LocalDateTime

33,786

Solution 1

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);

Solution 2

There are two ways to do it. If date property is under nested object then use comparator as follows

public int compare(Object obj1, Object obj2) {
 return obj2.getInnerObj().getLocalDateTime().compareTo(obj1.getInnerObj().getLocalDateTime());  }

If date property at the property of object then

List<Object> sortedList = objectList.stream()
           .sorted(Comparator.comparing(Object :: getLocalDateTime).reversed())
           .collect(Collectors.toList());

Solution 3

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.

Share:
33,786

Related videos on Youtube

Abdullah Asendar
Author by

Abdullah Asendar

Living in Jordan, originally from chechenya. studied software engineering at The Hashemite University. working as a full-time java developer at ReserveOut.com

Updated on July 05, 2022

Comments

  • Abdullah Asendar
    Abdullah Asendar almost 2 years

    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?

    • Jon Skeet
      Jon Skeet over 8 years
      Please show a short but complete program demonstrating the problem - ideally following Java naming conventions. (It appears that data is the name of both a type and a variable in your sample code - that's incredibly confusing.) I'd also suggest that if getDate() is a method returning a LocalDateTime, that's pretty poorly named...
  • Abdullah Asendar
    Abdullah Asendar over 8 years
    the data is ArrayList ,,sorry my bad
  • Basil Bourque
    Basil Bourque over 8 years
    @AbdullahAsendar If this Answer resolves your Question, please accept it. Hit the big empty check mark found by the up-vote and down-vote buttons.
  • Zon
    Zon about 5 years
    Also mind that this is a Void method, so data is immediately changed. No need to reassign the result.