Sunday, November 15, 2009


Comparing Two Dates

Here your will find the example to compare two dates in java. We use java.util.Date class and compareTo() method for comparison. The compareTo() method returns integer value when we comparing two dates.

The compareTo() method returns the following integer value if comparing two dates :

The integer value '0' returns if both dates are equal.
The integer value '1' returns when first date is greater than second date.
The integer value '-1' returns when first date is less than second date.

Here is the example of comparing 2 dates and display the final result :

import java.util.Date;
public class Comparedates{

public static void main(String[] args) {
Date Date1 = new Date();
try{
Thread.sleep(1000);
}catch(Exception e){
}
Date Date2 = new Date();
System.out.println("First Date:="+Date1);
System.out.println("Second Date:="+Date2);
if(Date1.compareTo(Date2) > 0)
System.out.println("Date1 is Greater than Date2");
else if(Date1.compareTo(Date2) < 0)
System.out.println("Date1 is less than Date2");
else
System.out.println("Date1 and Date2 are equal!!!");
}
}


0 comments: