Sunday 22 July 2012

How To Compare two java.util.Date objects using Calendar.Before(), Calendar.After() And Calendar.Equals()

We can use the following methods of java.util.Calendar class to compare two java.util.Date objects for ordering.


public boolean equals(Object obj)

Compares this Calendar to the specified Object.Returns true if and only if the argument is a Calendar object of the same calendar system that represents the same time value under the same Calendar parameters as this object.

public boolean before(Object when)

Returns whether this Calendar represents a time before the time represented by the specified Object.

public boolean after(Object when)

Returns whether this Calendar represents a time after the time represented by the specified Object.


The complete source code is given below:


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CompareDates {

 public static void main(String[] args) {
  try {

   SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
   Date date1 = sdf.parse("21-4-2008");
   Date date2 = sdf.parse("23-7-2012");

   System.out.println("Date1=" + sdf.format(date1));
   System.out.println("Date2=" + sdf.format(date2));

   Calendar cal1 = Calendar.getInstance();
   Calendar cal2 = Calendar.getInstance();
   cal1.setTime(date1);
   cal2.setTime(date2);

   if (cal1.after(cal2)) {
    System.out.println("Date1 is after Date2");
   }

   if (cal1.before(cal2)) {
    System.out.println("Date1 is before Date2");
   }

   if (cal1.equals(cal2)) {
    System.out.println("Date1 is equal Date2");
   }

  } catch (ParseException ex) {
   ex.printStackTrace();
  }
 }

}


The output is

Date1=21-04-2008
Date2=23-07-2012
Date1 is before Date2


The links that may help you:


No comments:

Post a Comment