Sunday 22 July 2012

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

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

public int compareTo(Date anotherDate)


where parameter anotherDate is the Date to be compared.

The method returns:

  • value 0 if the argument Date is equal to this Date.
  • value less than 0 if this Date is before the Date argument.
  • value greater than 0 if this Date is after the Date argument.

Th complete source code is given below:


import java.text.ParseException;
import java.text.SimpleDateFormat;
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));

   if (date1.compareTo(date2) > 0) {
    System.out.println("Date1 is after Date2");
   } else if (date1.compareTo(date2) < 0) {
    System.out.println("Date1 is before Date2");
   } else if (date1.compareTo(date2) == 0) {
    System.out.println("Date1 is equal to Date2");
   } else {
    System.out.println("How to get here?");
   }

  } 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