Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download a Free Sample PDF

How to Compare Two Dates in Java? Check If They Are Equal, Later or Earlier - Examples

There are multiple ways to compare two dates in Java, it also depends on 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 the equals() method of java.util.Date class. This method will return true if both dates are equal, precisely both have the 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 the 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 the before() and after() method of the 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 the date part without considering time, you need to use DateFormat class to format the date into some format and then compare their String value.

Alternatively, you can use joda-time which provides a class LocalDate, which represents a 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 the new Date and Time API.  

If you want to learn in-depth, you can also check out these Java 8 online courses to learn how to use the 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 an equality check then it makes sense to use the 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 the same millisecond they are considered equal. 


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 the given date instance and +1 if this date instance is greater than the given date instance.

All these methods perform a comparison based upon millisecond values only, as shown in the 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);
}

You can further see these free Java online courses to learn more about comparing Dates in Java and other fundamental concepts. 

How to Compare Two Dates in Java - Example




Java Program to compare Dates in Java

Here is our complete Java Program to compare Date objects in Java. You can use this code to try out yourself, you can just copy-paste and run in your IDE like Eclipse, or IntelliJIDEA. You can also run it from the command prompt using the java command. 
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

You can see that when that equals() method correctly returned false when we compared different dates. We have also used before() and after() method of Calendar class to check which date comes earlier and which date come later. 

Now, this example is good if you are using old java.util.Date class but if you are using new LocalDate class then  also you can use the equals() to check if they are equal or not as show in the following code example to compare date in Java. 


How to check if two LocalDate are equal in Java?

Here is the code example to check two LocalDate objects are equal sin Java:
import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        // Create two LocalDate objects
        LocalDate date1 = LocalDate.of(2022, 3, 30);
        LocalDate date2 = LocalDate.of(2022, 3, 30);

        // Check if the LocalDate objects are equal
        if (date1.equals(date2)) {
            System.out.println("The two LocalDate objects are equal.");
        } else {
            System.out.println("The two LocalDate objects are not equal.");
        }
    }
}
When you run this program, it will print "The two LocalDate objects are equal." because both date are same, but if you compare different dates, the equals() method will return false and it will print, "the two LocalDate objects are not equal", you can try that in your IDE. 


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 the Date class doesn't contain any timezone information. Date hold number of millisecond passed from 1st January 1970 in UTC. 

Related Java Date and Time Tutorials 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)

P. S. - 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 I mean any version before Java 8.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.