Sunday 22 July 2012

How To Compare two java.util.Date objects using Calendar.CompareTo()

We can use Calendar.compareTo() method to compare two java.util.Date objects for ordering.

public int compareTo(Calendar anotherCalendar)


Compares the time values represented by two Calendar objects, where parameter
anotherCalendar is the Calendar to be compared.


The method returns:


  • value 0 if the time represented by the argument is equal to the time represented by this Calendar. 
  • value less than 0 if the time of this Calendar is before the time represented by the argument. 
  • value greater than 0 if the time of this Calendar is after the time represented by the argument.

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("12-7-2010");
			Date date2 = sdf.parse("24-8-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.compareTo(cal2) > 0) {
				System.out.println("Date1 is after Date2");
			} else if (cal1.compareTo(cal2) < 0) {
				System.out.println("Date1 is before Date2");
			} else if (cal1.compareTo(cal2) == 0) {
				System.out.println("Date1 is equal to Date2");
			}

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

	}

}

The output is


Date1=12-07-2010
Date2=24-08-2012
Date1 is before Date2




The links that may help you:


No comments:

Post a Comment