Java Date - compareTo() Method
The java.util.Date.compareTo() method is used to compare two Dates for ordering. The method returns a value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
Syntax
public int compareTo(Date anotherDate)
Parameters
anotherDate |
Specify the Date to be compared. |
Return Value
Returns the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
Exception
Throws NullPointerException, if anotherDate is null.
Example:
In the example below, the java.util.Date.compareTo() method is used to compare given Dates.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating Dates Date Dt1 = new Date(); Date Dt2 = new Date(1000); Date Dt3 = new Date(2000); //comparing Dt1 with Dt2 System.out.println("Comparing Dt1 with Dt2: " + Dt1.compareTo(Dt2)); //comparing Dt1 with Dt3 System.out.println("Comparing Dt1 with Dt3: " + Dt1.compareTo(Dt3)); //comparing Dt1 with Dt1 System.out.println("Comparing Dt1 with itself: " + Dt1.compareTo(Dt1)); } }
The output of the above code will be:
Comparing Dt1 with Dt2: -1 Comparing Dt1 with Dt3: 1 Comparing Dt1 with itself: 0
❮ Java.util - Date