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;
// ja va2s  .  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;
//  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);

    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
Home » Java Tutorial » Date, Time, Calendar, TimeZone

Date

    Date class
    Date comparison
    Converting date value
    DateFormat class
    Format time
    DateFormat and Locale
    Convert String to Date

Calendar

    Calendar class
    Calendar date time getter
    Calendar set hour,minute,second
    Calendar calculation
    Calendar comparison
    Calendar properties
    GregorianCalendar

TimeZone

    TimeZone
    TimeZone ID and display name
    TimeZone daylight saving

DateFormat

    DateFormat class
    Format time
    DateFormat and Locale
    Convert String to Date
    SimpleDateFormat
    Parse date string into Date object
    SimpleDateFormat day format
    SimpleDateFormat Hour Time format
    SimpleDateFormat format minute
    SimpleDateFormat to format month
    SimpleDateFormat to format second value
    SimpleDateFormat to format TimeZone
    SimpleDateFormat to format year
    SimpleDateFormat to combine formatting flags