Online Training Spring Hibernate Training in Delhi R Programming Training Course Big Data and Hadoop Training Java Training

Comparing two dates in java

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

Ads

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

Advertisements

Share on Google+Share on Google+

Comparing two dates in java

Posted on: May 24, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: Comparing two dates in java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads