Online Hibernate Training just in Rs. 1000

One week online training in Hibernate ORM framework. Learn Hibernate Framework and enhance your skills. Best Online Hibernate training at 90% discount. Join Now!! Offer is valid Only for limited Period!!! Online Training

Comparing two Dates in Java

In this example we are going to compare two date objects using java.util.Date class. For comparing dates, we will be using compareTo() method.

Ads

Comparing two Dates in Java

     

In  this example we are going to compare two date objects using java.util.Date class. For comparing dates, we will be using compareTo() method. The compareTo() method returns integer value after comparing the dates.

In CompareDate example class we have defined firstDate object and then we used the Thread.Sleep(1000) method to make thread to sleep for 1 second and then it creates new object secondDate after. So that second date is created after one second of creation of firstDate. Now in our example program we can compare these two dates using compareTo() method.

firstDate.compareDate(secondDate);

  • firstDate.compareTo(secondDate) will return "0" when both dates are exactly equal
  • firstDate.compareTo(secondDate) will return "1" when firstDate is greater than secondDate and
  • firstDate.compareTo(secondDate) will return "-1" when firstDate is less than secondDate.

Here is the full example code of CompareDate class as follows:

CompareDate.java

import java.util.Date;
public class CompareDate{

  public static void main(String[] args) {
 Date firstDate = new Date();
  try{
  Thread.sleep(1000);
  }catch(Exception e){
  }
  Date secondDate = new Date();
  System.out.println("FirstDate:="+firstDate);
  System.out.println("SecondDate:="+secondDate);
  if(firstDate.compareTo(secondDate0)  
  System.out.println("Second Date is initialized before First Date");
  else if(firstDate.compareTo(secondDate0)
  System.out.println("Second Date is initialized after First Date");
  else
  System.out.println("First Date and Second Date are equal");
  }
}

Output:

C:\DateExample>javac CompareDate.java

C:\DateExample>java CompareDate
FirstDate:=Wed Oct 08 17:22:05 GMT+05:30 2008
SecondDate:=Wed Oct 08 17:22:06 GMT+05:30 2008
Second Date is initialized after First Date

Download Source Code

Advertisements

Share on Google+Share on Google+

Comparing two Dates in Java

Posted on: October 11, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Comparing two Dates in Java   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
Anonymous
August 3, 2012
comment

Awesome work done by RoseIndia.. Keep it up.. It helped me as lot.

Ads

 

Ads