Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Javadate Comparing two dates in java

Related Tutorials


 
 

Share on Google+Share on Google+

Comparing two dates in java

Advertisement
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.  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

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 24, 2013

Related Tutorials

Discuss: Comparing two dates in java  

Post your Comment


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