Compare two Date value

boolean after(Date when)
Tests if this date is after the specified date.
boolean before(Date when)
Tests if this date is before the specified date.
int compareTo(Date anotherDate)
Compares two Dates for ordering.
boolean equals(Object obj)
Compares two dates for equality.

Compare two Java Date objects using after method


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

public class Main {
  public static void main(String[] args) {
    Date d1 = Calendar.getInstance().getTime();

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, 2000);
    Date d2 = cal.getTime();
    
    System.out.println("First Date : " + d1);
    System.out.println("Second Date : " + d2);
    System.out.println("Is second date after first ? : " + d2.after(d1));
  }
}

The output:


First Date : Sat Oct 30 09:16:52 PDT 2010
Second Date : Mon Oct 30 09:16:52 PST 2000
Is second date after first ? : false

Compare two Java Date objects using compareTo method


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

public class Main {
  public static void main(String[] args) {
    Date d1 = Calendar.getInstance().getTime();

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, 2000);
    Date d2 = cal.getTime();

    System.out.println("First Date : " + d1);
    System.out.println("Second Date : " + d2);

    int results = d1.compareTo(d2);
    if (results > 0) {
      System.out.println("First Date is after second");
    } else if (results < 0) {
      System.out.println("First Date is before second");
    } else {
      System.out.println("equal");

    }
  }
}
  

The output:


First Date : Sat Oct 30 09:17:18 PDT 2010
Second Date : Mon Oct 30 09:17:18 PST 2000
First Date is after second
Home 
  Java Book 
    Essential Classes  

Date:
  1. Date class
  2. Create Date object
  3. Compare two Date value
  4. Convert date value to long value in milliseconds
  5. Convert Date value to String