Date comparison

In this chapter you will learn:

  1. Methods to compare two dates
  2. Compare two Java Date objects using compareTo method

Methods to compare two dates

  • 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.

The following code compares two Java Date objects using after method.

import java.util.Calendar;
import java.util.Date;
/*from j a v  a  2  s  . c o m*/
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:

Compare two Java Date objects using compareTo method

import java.util.Calendar;
import java.util.Date;
//from jav  a 2 s . c o  m
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:

Next chapter...

What you will learn in the next chapter:

  1. Convert date value to long value in milliseconds
  2. Convert Date value to String