Compare Dates in Java

In this post, we will see how to compare two dates in Java.

 

1. Date.compareTo()

We can compare two java.util.Date dates by using Date.compareTo() method. It returns

  1. value = 0, if both dates are equal
     
  2. value < 0, if Date is before the specified argument
     
  3. value > 0, if Date is after the specified argument

 

Download   Run Code

Output:

10-20-2016 is after 10-12-2015

 
In Java 8, we can use compareTo() method to compare java.time.LocalDate, java.time.LocalTime and java.time.LocalDateTime.

 

Download   Run Code

Output:

10-20-2016 is after 10-12-2015

 

2. Date.before(), Date.after() and Date.equals()

The java.util.Date class provides three methods - before(), after() and equals(), which returns a boolean value based on the comparison result.

  1. Date.after() returns true if the date is after the specified date.
     
  2. Date.before() returns true if the date is before the specified date.
     
  3. Date.equals() returns true if both dates are equal.

 

Download   Run Code

Output:

10-20-2016 is after 10-12-2015

 

3. Calender.before(), Calender.after() and Calender.equals()

The java.util.Calendar class also provides three methods - before(), after() and equals(), which can be used to compare two java.util.Date. This method should be avoided.

 

Download   Run Code

Output:

10-20-2016 is after 10-12-2015

 

4. Java 8 - isBefore(), isAfter(), isEqual() methods

In Java 8, we can use isBefore(), isAfter(), isEqual() methods to compare java.time.LocalDate, java.time.LocalTime and java.time.LocalDateTime.

 

Download   Run Code

Output:

10-20-2016 is after 10-12-2015

 
References: Date (Java Platform SE 8)

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Leave a Reply

avatar
  Subscribe  
Notify of