Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare LocalDate instances Java 8

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

like image 708
azalut Avatar asked Mar 22 '15 23:03

azalut


People also ask

What is the difference between two LocalDateTime in Java 8?

getDays() + " days " + time[0] + " hours " + time[1] + " minutes " + time[2] + " seconds.");

Does LocalDate implement comparable?

2 Answers. Show activity on this post. LocalDate in fact implements Comparable<ChronoLocalDate> as well as ChronoLocalDate and by implementing those two, every instance of it is of course comparable to another LocalDate instance. You can have a look at the JavaDocs for LocalDate on Oracle's website.


2 Answers

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.

  • isAfter()
  • isBefore()
  • isEqual()

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

like image 93
royB Avatar answered Oct 06 '22 12:10

royB


LocalDate ld ....; LocalDateTime ldtime ...;  ld.isEqual(LocalDate.from(ldtime)); 
like image 30
Stepi Avatar answered Oct 06 '22 12:10

Stepi