This post will discuss how to compare two dates in Java.

1. Using java.util.Date class

To compare two java.util.Date objects, we can use the compareTo() method. This method returns an integer value indicating the order of the two dates, by comparing the specified date with the current date based on their millisecond values. The return value is 0 if the dates are equal, negative if the current date is earlier than the specified date, and positive if the current date is later than the specified date. The following program demonstrates its usage:

Download  Run Code

Output:

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

 
The java.util.Date class also offers three more methods: before(), after() and equals(), which returns a boolean value depending upon the comparison result. The Date.after() method checks whether the date is later than the specified date, the Date.before() method checks whether the date is before than the specified date, and the Date.equals() method compares whether the dates are the same. The following program demonstrates its usage:

Download  Run Code

Output:

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

2. Using java.time.LocalDate class

In Java 8, we can use the LocalDate class from the java.time package, which represents a date without time and timezone information. We can compare two dates using the compareTo(), which returns a negative, zero, and positive value indicating whether the current date is before, equal to, or after the specified date, respectively. Here is an example of using this method:

Download  Run Code

Output:

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

 
We can also use java.time.LocalDateTime class that represents a date with time, without timezone information. The java.time.LocalDate and java.time.LocalDateTime class also offers three more methods: isAfter(), isBefore(), isEqual() method, which compares the date object with another date and return a boolean value depending on whether the date object is later than, earlier than, or equal to the other date, respectively. These methods compare the dates based on their chronological order. The following program demonstrates its usage:

Download  Run Code

Output:

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

That’s all about comparing two dates in Java.