Comparing two dates in java

In this example you will learn how to compare two dates in java.

Comparing two dates in java

In this example you will learn how to compare two dates in java.

Comparing two dates in java

Comparing two dates in java

In this example you will learn how to compare two dates in java.  java.util.Date provide a  method to compare two dates. The method which is used to compare the dates is "compareTo() ". It returns three values  i.e. 1 if  first date is greater then second date, 0 if both dates are equal and -1 if second date is greater than first date. The example below compares the two dates.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
  public class CmpareDate
 {
   public static void main(String args[]) throws ParseException
  {
   SimpleDateFormat sd=new SimpleDateFormat("dd-mm-yyyy");
   Date date1=sd.parse("12-12-2012");
   Date date2=sd.parse("11-08-2000");
     if(date1.compareTo(date2)>0)
     {
      System.out.println("First date is greater then second date");
     }
      else if(date1.compareTo(date2)==0)
      {
       System.out.println("Date1 and date 2 are equals");
      }
      else if(date1.compareTo(date2)<0)
      {
        System.out.println("Date 2 is greater then date1");
       }
   }
} 

Output :  First date is greater then second date.

Download SourceCode