Search code examples
javadatecomparisonboolean-expressioncomparison-operators

How to compare dates in Java using comparison operators?


How do I compare dates in Java using comparison operators?

Example:

date1 is 30-10-2017
date2 is 31-10-2017
date3 is 30-10-2018

date2 returns false when it should be true that it is less than date3. How can I return true if the date is less than another date and false otherwise?

This is my code:
return (day < theDate.day) || (month < theDate.month) || (year < theDate.year);

Below is my current solution:

{
  boolean check = false;
  if(year < theDate.year)
  {
      return true;
  }
  if(year > theDate.year)
  {
      return false;
  }
  if(month < theDate.month)
  {
      check = true;
  }
  if(day < theDate.day)
  {
      check = true;
  }
  else
  {
      return false;
  }
  return check;
}

Solution

  • LocalDate date1 = LocalDate.of(2017, 10, 30); // Year, month, day.
    LocalDate date2 = LocalDate.of(2017, 10, 31);
    LocalDate date3 = LocalDate.of(2018, 10, 30);
    
    System.out.printf("%s before %s? %s%n", date1, date2, date1.isBefore(date2));
    System.out.printf("%s before %s? %s%n", date2, date3, date3.isBefore(date3));
    System.out.printf("%s before %s? %s%n", date3, date1, date3.isBefore(date1));
    

    If you want to know how to do a comparison yourself:

    • Compare first year, then month, then day: from most significant to least
    • For this reason the ISO standard of denoting dates (and times) is 2017-09-30T13:05:01,000 where a text comparison with a representation of the same length suffices.

    And the pattern goes:

    1. if years not equal then result found
    2. if months not equal then result found
    3. result is comparison of days