Java - LocalDate comparison out of range but incorrect output

null.ts :

Im trying to compare two dates against a list of dates (list element has been removed as it would require more classes provided so i am just giving the base requirements for it to run)

The two dates the list is comparing to is a date range to identify objects which are within this range

When two CORRECT dates are provided as a range the output is fine

the problem occurs when an incorrect range is provided (end date is before start date) an invalid date range is not outputted

package test;

import java.time.LocalDate;

public class A1 {

    public void searchEnrolments(int StartDay, int StartMonth, int StartYear, int EndDay, int EndMonth, int EndYear) {
           LocalDate a = LocalDate.of(StartYear, StartMonth, StartDay);
           LocalDate b = LocalDate.of(EndYear, EndMonth, EndDay);   
           boolean before = a.isBefore(b);
           if (before = true) {
                   System.out.println("Out of range: ");
                   }
          else {
                 System.out.println("Invalid Date Range");
               }
          }
}

package test;
public class aTester {
    public static void main(String[] args) {
        A1 a2= new A1();
        a2.searchEnrolments(20, 04, 2020, 10, 02, 2019);
    }
}
Dhruv Saksena :

This is happening because you are not using "==" equals opeator. You are assigning the value in the if-clause.

Just replace the if clause-

 if (before == true) {
                   System.out.println("Out of range: ");
                   }
          else {
                 System.out.println("Invalid Date Range");
               }
          } 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=409637&siteId=1