How to compare LocalDate instances Java 8

DateCompareJava 8

Date Problem Overview


I am writing an app that needs to be quite accurate in dates and I wonder how can I compare LocalDate instances.. for now I was using something like:

LocalDate localdate1 = LocalDate().now();
LocalDate localdate2 = someService.getSomeDate();
localdate1.equals(localdate2);

But I noticed that my app is giving me some confusing results, and I think it is because of the date comparing.

I am thinking about obtaining the time from 1970' in long and compare those two, but I must be easier, I am sure of it

Date Solutions


Solution 1 - Date

Using equals() LocalDate does override equals:

int compareTo0(LocalDate otherDate) {
    int cmp = (year - otherDate.year);
    if (cmp == 0) {
        cmp = (month - otherDate.month);
        if (cmp == 0) {
            cmp = (day - otherDate.day);
        }
    }
    return cmp;
}

If you are not happy with the result of equals(), you are good using the predefined methods of LocalDate.

Notice that all of those method are using the compareTo0() method and just check the cmp value. if you are still getting weird result (which you shouldn't), please attach an example of input and output

Solution 2 - Date

LocalDate ld ....;
LocalDateTime ldtime ...;

ld.isEqual(LocalDate.from(ldtime));

Solution 3 - Date

I believe this snippet will also be helpful in a situation where the dates comparison spans more than two entries.

static final int COMPARE_EARLIEST = 0;

static final int COMPARE_MOST_RECENT = 1;


public LocalDate getTargetDate(List<LocalDate> datesList, int comparatorType) { 
   LocalDate refDate = null;
   switch(comparatorType)
   {
	   case COMPARE_EARLIEST:         
       //returns the most earliest of the date entries
	      refDate = (LocalDate) datesList.stream().min(Comparator.comparing(item -> 
            		  item.toDateTimeAtCurrentTime())).get();
	      break;

	   case COMPARE_MOST_RECENT:
          //returns the most recent of the date entries 
	      refDate = (LocalDate) datesList.stream().max(Comparator.comparing(item -> 
            		item.toDateTimeAtCurrentTime())).get();
	      break;
   }

   return refDate;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionazalutView Question on Stackoverflow
Solution 1 - DateroyBView Answer on Stackoverflow
Solution 2 - DateStepiView Answer on Stackoverflow
Solution 3 - DateChigozie D.View Answer on Stackoverflow