Wednesday, September 18, 2024

5 Examples to Compare two Dates in Java?

Comparing dates in Java is a common task for Java programmers, now and then we need to compare two dates to check whether two dates are equals, less than, or greater than each other, sometimes we also need to check if one date comes in between two dates. Java provides multiple ways to compare two Dates in Java which is capable of performing Date comparison and letting you know whether two dates are the same, one date comes before or after another date in Java. By the way, when you compare dates, make sure to consider timezones, day light saving time, and precision. 

In the last couple of articles, we have seen how to convert String to Date in Java and Converting  Date to String in Java and here we will see three different examples of comparing two dates in Java.


How to compare two dates in Java? 5 Examples

There are multiple ways to compare two dates in Java and below is 3 ways I used to compare multiple dates in Java"

  1) by Using the classic CompareTo method of Date class.

  2) by using equals(), before() and after() methods of Date class.

  3) by using equals(), before() and after()  methods of Calendar class in Java.

  4) by using Java 8 LocalDate/LocalDateTime

  5) by using Instant comparison (Java 8+):

All three ways are capable of performing date comparison but my favorite is either using compareTo be in consistent with how we compare two objects in Java or by using Date's equals(), before and after() method because that sounds more natural to me.  

There are few more other ways which I have documented in this diagram:




Here is a code example of comparing different dates in Java.



import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class HashtableDemo {

    public static void main(String args[]) throws AssertionError, ParseException {

        DateFormat df = new SimpleDateFormat("dd-MM-yyyy");

        //comparing date using compareTo method in Java
        System.out.println("Comparing two Date in Java using CompareTo method");
        compareDatesByCompareTo(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
        compareDatesByCompareTo(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
        compareDatesByCompareTo(df, df.parse("02-03-2012"), df.parse("01-02-2012"));

        //comparing dates in java using Date.before, Date.after and Date.equals
        System.out.println("Comparing two Date in Java using Date's before, after and equals method");
        compareDatesByDateMethods(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
        compareDatesByDateMethods(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
        compareDatesByDateMethods(df, df.parse("02-03-2012"), df.parse("01-02-2012"));

        //comparing dates in java using Calendar.before(), Calendar.after and Calendar.equals()
        System.out.println("Comparing two Date in Java using Calendar's before, after and equals method");
        compareDatesByCalendarMethods(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
        compareDatesByCalendarMethods(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
        compareDatesByCalendarMethods(df, df.parse("02-03-2012"), df.parse("01-02-2012"));

    }

    public static void compareDatesByCompareTo(DateFormat df, Date oldDate, Date newDate) {
        //how to check if date1 is equal to date2
        if (oldDate.compareTo(newDate) == 0) {
            System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
        }

        //checking if date1 is less than date 2
        if (oldDate.compareTo(newDate) < 0) {
            System.out.println(df.format(oldDate) + " is less than " + df.format(newDate));
        }

        //how to check if date1 is greater than date2 in java
        if (oldDate.compareTo(newDate) > 0) {
            System.out.println(df.format(oldDate) + " is greater than " + df.format(newDate));
        }
    }

    public static void compareDatesByDateMethods(DateFormat df, Date oldDate, Date newDate) {
        //how to check if two dates are equals in java
        if (oldDate.equals(newDate)) {
            System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
        }

        //checking if date1 comes before date2
        if (oldDate.before(newDate)) {
            System.out.println(df.format(oldDate) + " comes before " + df.format(newDate));
        }

        //checking if date1 comes after date2
        if (oldDate.after(newDate)) {
            System.out.println(df.format(oldDate) + " comes after " + df.format(newDate));
        }
    }

    public static void compareDatesByCalendarMethods(DateFormat df, Date oldDate, Date newDate) {

        //creating calendar instances for date comparision
        Calendar oldCal = Calendar.getInstance();
        Calendar newCal = Calendar.getInstance();

        oldCal.setTime(oldDate);
        newCal.setTime(newDate);

        //how to check if two dates are equals in java using Calendar
        if (oldCal.equals(newCal)) {
            System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
        }

        //how to check if one date comes before another using Calendar
        if (oldCal.before(newCal)) {
            System.out.println(df.format(oldDate) + " comes before " + df.format(newDate));
        }

        //how to check if one date comes after another using Calendar
        if (oldCal.after(newCal)) {
            System.out.println(df.format(oldDate) + " comes after " + df.format(newDate));
        }
    }
}

Output:

Comparing two Date in Java using CompareTo method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 is less than 04-05-2012
02-03-2012 is greater than 01-02-2012
Comparing two Date in Java using Date's before, after and equals method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 comes before 04-05-2012
02-03-2012 comes after 01-02-2012
Comparing two Date in Java using Calendar's before, after and equals method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 comes before 04-05-2012
02-03-2012 comes after 01-02-2012


From JDK 8 onwards you can also use modern ways to compare dates in Java. 

For example, you can use Instant comparison or use the methods isBefore() or isAfter() provided by new Date and Time API


4. Using Instant comparison (Java 8+)

This code can compare dates up to nanosecond precision

instant1.compareTo(instant2) or instant1.equals(instant2)


5. Using Java 8 LocalDate/LocalDateTime

Similarly you can use following code to compare dates in modern way in Java, these method returns boolean which makes your code easier to read

date1.isEqual(date2), 
date1.isBefore(date2), 
date1.isAfter(date2)




example of date compare in javaThat’s all on comparing two dates in Java. Dates are very important for writing any enterprise java application and a good understanding of Dates and Calendar classes, Date Formatting always helpsYou can also see these Java Programming courses to learn more about essential Java concepts like Date and Time etc. 


Here are few more Java tutorials you may like.

3 comments:

  1. good examples. I would recommend Joda time API for comparing dates or any date related operation in java.

    ReplyDelete
  2. @Anonymous, yes Joda Time could be good choice as well but it also add another dependency on your project.

    ReplyDelete
  3. What is the best way to compare dates without time in Java? I mean comparing dates and ignoring times even if they have?

    ReplyDelete