Compare two Date value

ReturnMethodSummary
booleanafter(Date when)Tests if this date is after the specified date.
booleanbefore(Date when)Tests if this date is before the specified date.
intcompareTo(Date anotherDate)Compares two Dates for ordering.
booleanequals(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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.