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(secondDate) > 0)
System.out.println("Second Date is initialized before First Date");
else if(firstDate.compareTo(secondDate) < 0)
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

|