The compareTo() method of Java Date class compares two dates and sort them for order.
public int compareTo(Date anotherDate)
Parameters: The function accepts a single parameter anotherDate which specifies the date to be compared .
Return Value: The function gives three return values specified below:
- It returns the value 0 if the argument Date is equal to this Date.
- It returns a value less than 0 if this Date is before the Date argument.
- It returns a value greater than 0 if this Date is after the Date argument.
Exception: The function throws a single exception that is NullPointerException if anotherDate is null.
Program below demonstrates the above mentioned function:
Date 1: Thu Dec 05 08:17:55 UTC 1996 Date 2: Wed Jan 02 08:17:55 UTC 2019 On Comparison: 1
Date 1: Wed Jan 02 08:18:02 UTC 2019 Date 2: null Passing null as parameter: Exception: java.lang.NullPointerException
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.