How to compare two dates in Java? Examples

There are multiple ways to compare two dates in Java, it also depends on upon what exactly comparison means. If you are looking to compare two dates to find out whether they are equal or not, then you can simply use equals() method of java.util.Date class. This method will return true if both dates are equal, precisely both thave same millisecond value. If you are looking to find out whether a date comes before or after another date then you have 3 choices, you can use compareTo() method of java.util.Date class, or you can use before() and after() method of Date class, or you can use before() and after() method of Calendar class. I suggest leveraging before() and after() method of Date class, they are more readable and easy to use.

BTW, all these methods compare date at the millisecond level, which means they take both date and time into account. If you want to compare just date part without considering time, you need to use DateFormat class to format date into some format and then compare their String value.

Alternatively, you can use joda-time which provides a class LocalDate, which represents date without time, similar to Java 8's LocalDate class. If you are running in Java 8, then there is no reason not to use new Date and Time API.  If you are in a hurry, then see Java SE 8 for Really Impatient by Cay S. Horstmann to learn how to use new Date and Time API of Java 8 in your old and new Java application.



How to check if two dates are equal in Java

There are two ways to check if two dates are equal in Java :
  • Date's equals() method - return true if two dates are equal
  • Date's compareTo() method - return zero if two dates are equal


If you are doing equality check then it make sense to use equals() method. It does comparison by checking millisecond values of given dates as shown below :

public boolean equals(Object obj) {
   return obj instanceof Date && getTime() == ((Date) obj).getTime();
}

So, if two dates have same millisecond they are considered equal. See Java How to Program by Dietel for more examples.


How to check if a date comes before or after another

There are three ways to check if one date comes before or after another date in JDK, without using any third party library like joda.

1) Date's before() and after() method - will return true or false
2) Calendar's before() and after() method - return true or false
3) Date's compareTo() method - return -1 if this date instance is less than given date instance and +1 if this date instance is greater than given date instance.

All these methods perform a comparison based upon millisecond values only, as shown in below code of before() and after() methods of java.util.Date class :

public boolean before(Date when) {
   return getMillisOf(this) < getMillisOf(when);
}

public boolean after(Date when) {
   return getMillisOf(this) > getMillisOf(when);
}

See Core Java, Volume 1 - Fundamentals by Cay S. Horstmann to learn more about comparing Dates in Java.

















Java Program to compare Dates in Java

package dto;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * 2 ways to compare given dates in Java without using
 * any third party library e.g. joda time.
 * 
 * @author WINDOWS 8
 *
 */
public class DateComparator {

    public static void main(String args[]) {
       Calendar todayCalendar = new GregorianCalendar(2015, Calendar.AUGUST, 24);
       Calendar yesterdayCalendar = new GregorianCalendar(2015, Calendar.AUGUST, 23);
       
       Date today = todayCalendar.getTime();
       Date yesterday = yesterdayCalendar.getTime();
       
       // comparing dates using equals() method in Java
       // today and yesterday is not equal
       if(today.equals(yesterday)){
           System.out.println("two given dates are equal to each other");
       }else{
           System.out.println("two dates are not equal to each other ");
       }
       
       
       // you can also check if two dates are equal or not using
       // compareTo() method, java.util.Date implements 
       // Comparable and its compareTo() is consistent with equals()          
       if(yesterday.compareTo(today) == 0){
           System.out.println("Given dates are same");
       }else{
           System.out.println("Given dates are different ");
       }
       
       
       // checking which dates comes first 
       // you can use before() and after() method of Calendar class
       if(todayCalendar.after(yesterdayCalendar)){
           System.out.println("first date comes after second date");
       }
       
       // Date class also has their own before() and after() method
       if(yesterday.before(today)){
           System.out.println("yesterday comes before today");
       }
    }

    
}

Output
two dates are not equal to each other 
Given dates are different 
the first date comes after the second date
yesterday comes before today


That's all about how to compare two dates in Java. When you compare dates, it takes both date and time into consideration, because it compares on long millisecond value. Also remember that Date class doesn't contain any timezone information. Date hold number of millisecond passed from 1st January 1970 in UTC. If you want to compare dates without taking time into consideration, consider using Java 8 new Date and Time API or joda-time, if you are running on Java SE 5, 6 or 7.

Related Java Date and Time tutorial for Programmers
  • How to convert java.sql.Date to java.util.Date in Java? (example)
  • How to get the current Timestamp in Java? (answer)
  • Difference between java.util.Date and java.sql.Timestamp in JDBC? (answer)
  • How to format Date in Java using SimpleDateFormat? (example)
  • How to convert String to Date in Java? (answer)
  • How to display Date in multiple timezones in Java? (example)
  • How to convert java.util.Date to java.sql.Date in JDBC? (answer)
  • How to convert java.util.Date to java.sql.Timestamp in JDBC? (example)
  • How to parse String to Date in Java using JodaTime library? (example)


References
Java SE 8 documentation of Date class
Java Se 8 documentation of Timestamp class




No comments:

Post a Comment