How to Compare Dates in Java

In this tutorial you will learn how to compare dates in Java.

There are mainly three different ways to compare two dates in Java.

1. Using compareTo() method
2. Using equals(), before() and after() method
3. Using getTime() method

Below I have shared one example for each of these methods.

How to Compare Dates in Java

How to Compare Dates in Java

compareTo()

We can use compareTo() method of java.util.Date class to compare dates in Java. Let say we are comparing date1 and date2 by date1.compareTo(date2). It returns following result.

Return 0 if date1 and date2 are equal.
Return value less than 0 if date1 is before date2.
Return value more than 0 if date1 is after date2.

 

Output

Date1 and Date2 are equal

 

equals(), before() and after()

These are user friendly methods used to compare dates in Java. They are available in java.util.Date class.

equals() method returns true if two dates are equal, otherwise returns false.
before() method returns true if first date is before second date, otherwise returns false.
after() method returns true if first date is after second date, otherwise returns false.

 

Output

Date1 is before Date2

 

getTime()

The getTime() method of java.util.Date class can be also used to compare dates in Java. getTime() method returns the number of milliseconds since January 1, 1970. Below example shows how it can be used.

 

Output

Date1 is after Date2

 

If you found anything incorrect or have doubts related to above Java compare dates tutorial then feel free to comment below.

One thought on “How to Compare Dates in Java

  1. Abhishek

    Plz post sonething on how to get no of days between two dates..

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *