Comparing two dates in JAVA

Comparing date with Calendar class in java.

Date class is going to depreciated with most of methods. Date should be used with Calendar class. We can compare two dates in java with compareTo() method
Comparing date can be done by also after(), before() and equals() method.

compareTo() method return 3 values

Return 0, means dates are equal
Return 1, if first date is greater than second date
Return -1, if first date is less than second date

Example of two date comparing

import java.util.Calendar;
public class MyDate {

    public static void main(String[] args) {

          Calendar c1=Calendar.getInstance();
          c1.set(2009,22,05);

          Calendar c2=Calendar.getInstance();
          c2.set(2009,23,05);

          if(c1.compareTo(c2)<0)
           {
               // return -1 if date1 is less than date2
               System.out.println("1. Date1 is less than date2");
           }
           else if(c1.compareTo(c2)>0)
           {
               // return 1 if date1 is greater than date2
               System.out.println("1. Date1 is greater than date2");
           }
           else
           {
               // return 0 if date1 is equal to date2
               System.out.println("1. Date1 is equal to date2");
           }

          /**
           *  Compare date with after(), before() and equals() method
           */

          if(c1.after(c2))
           {
               //  if date1 is greater than date2
               System.out.println("2. Date1 is greater than date2");
           }
           else if(c1.before(c2))
           {
               // if date1 is less than date2
               System.out.println("2. Date1 is less than date2");
           }
           else if(c1.equals(c2))
           {
               // if date1 is equal to date2
               System.out.println("2. Date1 is equal to date2");
           }
    }
}

Tags:

Bookmark  

 

Leave a Reply

Security Code:

 

  Random Post