How to compare dates in Java?

You can compare dates in Java by using the compareTo() method of the java.util.Date class. This method compares the date object on which it is called with the date object passed as an argument to the method, and returns an integer value indicating whether the date is before, after, or the same as the argument date.

Here is an example of how you can use compareTo() to compare two dates in Java:

import java.util.Date;

public class DateComparisonExample {
  public static void main(String[] args) {
    Date date1 = new Date();
    Date date2 = new Date();

    // Compare date1 and date2
    int result = date1.compareTo(date2);
    if (result == 0) {
      System.out.println("date1 and date2 are the same");
    } else if (result < 0) {
      System.out.println("date1 is before date2");
    } else {
      System.out.println("date1 is after date2");
    }
  }
}

If you want to compare dates without taking into account the time portion of the date, you can use the java.util.Calendar class to set the time portion of the dates to be the same before performing the comparison. Here is an example of how you can do this:

import java.util.Calendar;
import java.util.Date;

public class DateComparisonExample {
  public static void main(String[] args) {
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();

    // Set both calendars to be at midnight
    cal1.set(Calendar.HOUR_OF_DAY, 0);
    cal1.set(Calendar.MINUTE, 0);
    cal1.set(Calendar.SECOND, 0);
    cal1.set(Calendar.MILLISECOND, 0);
    cal2.set(Calendar.HOUR_OF_DAY, 0);
    cal2.set(Calendar.MINUTE, 0);
    cal2.set(Calendar.SECOND, 0);
    cal2.set(Calendar.MILLISECOND, 0);

    // Compare the two calendars
    int result = cal1.compareTo(cal2);
    if (result == 0) {
      System.out.println("cal1 and cal2 are the same");
    } else if (result < 0) {
      System.out.println("cal1 is before cal2");
    } else {
      System.out.println("cal1 is after cal2");
    }
  }
}