Search code examples
javalocaldate

Which operator should I use to compare two LocalDate values?


I am giving a LocalDate value and then I want to give another one but I want to make sure that the new one is not the same with the one before. I wrote some code but doesn't seem to be working.

Flight flight = new Flight();
System.out.println("Give the day of the departure.");
LocalDate day = LocalDate.of(2019, Month.MAY, scanner.nextInt());
flight.setDateOfDeparture(day);
boolean theDay = true; //Flag (reversed way in order to achieve the TRUE logic value).

for (Flight flight1 : flightList) {
    if (flight1.getDateOfDeparture() == (flight.getDateOfDeparture())) {
           theDay = false;
     }
}

if (theDay) {
    // Some logic...
}

I tried also the keyword equals. but again the for loop ignores the compare.

for (Flight flight1 : flightList) {
   if (flight1.getDateOfDeparture().equals(flight.getDateOfDeparture())) {
        theDay = false;
   }
}

After your answers I tried many of the solutions you proposed. To check if the compiler gets into for loop I put a print message of the variable which is never seen to my console.

for (Flight flight1 : flightList) {
   System.out.println(flight1.getDateOfDeparture());
   if(flight1.getDateOfDeparture().compareTo(flight.getDateOfDeparture())==0) {
      theDay = false;
    }
}

Solution

  • You can use below methods according to your needs

        LocalDate oldDate = LocalDate.of(2019,3,31);
        LocalDate newDate = LocalDate.of(2019,4, 1);
        System.out.println(oldDate.isAfter(newDate));
        System.out.println(oldDate.isBefore(newDate));
        System.out.println(oldDate.isEqual(newDate));
        System.out.println(oldDate.compareTo(newDate));
    

    This will return

    false
    true
    false
    -2