Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Compare dates
3.
Date.compareTo() Method
4.
Java Date Class
5.
Java Calendar Class 
6.
Java LocalDate Class
7.
Frequently Asked Questions
7.1.
What is the return type of compareTo ()?
7.2.
What's the difference between the Calendar and Date classes in Java?
7.3.
What are the getInstance () methods in the Java calendar class?
8.
Conclusion
Last Updated: Mar 27, 2024

Compare Dates in Java

Author Aditi
0 upvote

Introduction

When working with dates and times in Java, we occasionally need to compare dates. In Java, comparing two dates is different from comparing two numbers. So, comparing two dates in Java is a bit of a challenge. To compare dates, we don't need to use any reasoning. Java includes methods like compareTo(), before(), after(), and equals() to make this work easier. We will learn how to compare two dates in Java in this blog.

Also Read About, Multithreading in java

Compare dates

In Java, four classes provide methods for comparing two dates.

  • Making use of the compareTo() method
  • Making use of the Date Class
  • Making use of Calendar Class
  • Making use of the LocalDate Class
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Date.compareTo() Method

The Java Date class has several methods that deal with time and dates. It's java.util package class. The Serializable, Cloneable and Comparable < date> interfaces are all implemented by this class. The class provides the compareTo() method for comparing two dates. For orders, it compares dates as an argument; it parses a date (to be compared). If the date parameter is null, it raises a NullPointerException.

Syntax:-

public int compareTo(Date anotherDate)

It returns the following integer values:-

  • If the dates are equal, the result is 0.
  • If the date is before the given date, the value is less than 0.
  • If the date is later than the argument date, the value is greater than 0.
     

Program:-

import java.util.Date;  
import java.text.SimpleDateFormat;  
import java.text.ParseException;  
public class Main
{  
    public static void main(String[] args) throws ParseException  
    {  
        //object of SimpleDateFormat class  
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");  
        //dates to be compare  
        Date d1 = dateFormat.parse("10-05-2022");  
        Date d2 = dateFormat.parse("20-06-2021");  
        //prints dates  
        System.out.println("Date 1: " + dateFormat.format(d1));  
        System.out.println("Date 2: " + dateFormat.format(d2));  
        //comparing dates  
        if(d1.compareTo(d2) > 0)  
        {  
            System.out.println("Date 1 comes after Date 2");  
        }  
        else if(d1.compareTo(d2) < 0)  
        {  
            System.out.println("Date 1 comes before Date 2");  
        }  
        else if(d1.compareTo(d2) == 0)  
        {  
            System.out.println("Both dates are equal");  
        }  
    }  
}  

Output:-

Date 1: 10-05-2022
Date 2: 20-06-2021
Date 1 comes after Date 2

Java Date Class

To compare two dates, the Java date class includes before(), after(), and equals() methods.

before(): This method determines whether the date falls before or after the supplied date. It parses a Date-type parameter. It returns true if and only if the time represented by this Date object is strictly earlier than the time represented by when; otherwise, it returns false. If it is null, it throws a NullPointerException.

Syntax:-

public boolean before(Date d)  

after(): This method determines if the date is after or before the supplied date. It parses a Date-type parameter. It returns true if and only if the time represented by this Date object is strictly later than the time represented by when; otherwise, it returns false. If it is null, it throws a NullPointerException.

Syntax:-

public boolean after(Date d)  

equals(): This method compares two dates to see if they are equal. It overrides the Object class's equals() method. If the objects are the same, it returns true; otherwise, it returns false. As a result, the Date objects will be equal if the getTime() method for both dates returns the same long value.

Syntax:-

public boolean equals (Object obj)  

 

Program:-

import java.util.Date;  
import java.text.ParseException;  
import java.text.SimpleDateFormat;  
public class Main
{  
    public static void main(String args[]) throws ParseException  
    {  
        //Creating an object of the SimpleDateFormat class  
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");  
       
        Date d1 = dateFormat.parse("10-10-2021");  
        Date d2 = dateFormat.parse("10-10-2020");  
       
        System.out.println("Date 1: " + dateFormat.format(d1));  
        System.out.println("Date 2: " + dateFormat.format(d2));  
       
        //Comparing the two dates  
        if (d1.after(d2))  
        {  
            //if date1>date2, prints the following statement  
            System.out.println("Date 1 comes after Date 2");  
        }  
        else if (d1.before(d2))  
        {  
            //if date1<date2, prints the following statement  
            System.out.println("Date 1 comes before Date 2");  
        }  
        else if (d1.equals(d2))  
        {  
            //date1=date2 prints the following statement  
            System.out.println("Both dates are equal");  
        }  
    }  
}  

Output:-

Date 1: 10-10-2021
Date 2: 10-10-2020
Date 1 comes after Date 2

 

Try and compile it on java online compiler.

Java Calendar Class 

Let's compare two dates using the Calendar class's after(), before(), and equals() methods. Except for the getInstance() and setTime() methods, we used the same procedure as in the previous example and the following.

getInstance(): The Calendar has a static function called getInstance(). It returns a Calendar with the time zone and locale set to the defaults.

Syntax:-

public static Calendar getInstance()   

setTime(): This method changes the calendar time to the current date. It parses a Date-type parameter.

Syntax:-

public final void setTime(Date date)  

 

Program:-

import java.util.Date;  
import java.util.Calendar;  
import java.text.ParseException;  
import java.text.SimpleDateFormat;  
public class Main
{  
    public static void main(String args[]) throws ParseException  
    {  
        //Creating an object of the SimpleDateFormat class  
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");  
       
        Date d1 = dateFormat.parse("10-10-2021");  
        Date d2 = dateFormat.parse("10-10-2021");  
       
        System.out.println("Date 1: " + dateFormat.format(d1));  
        System.out.println("Date 2: " + dateFormat.format(d2));  

        //invoking getInstance() method  
        Calendar c1 = Calendar.getInstance();  
        Calendar c2 = Calendar.getInstance();  
        c1.setTime(d1);  
        c2.setTime(d2);  
       
        //Comparing the two dates  
        if (c1.after(c2))  
        {  
            //if date1>date2  
            System.out.println("Date 1 comes after Date 2");  
        }  
        else if (c1.before(c2))  
        {  
            //if date1<date2
            System.out.println("Date 1 comes before Date 2");  
        }  
        else if (c1.equals(c2))  
        {  
            //date1=date2
            System.out.println("Both dates are equal");  
        }  
    }  
}  

Output:-

Date 1: 10-10-2021
Date 2: 10-10-2021
Both dates are equal

You can also read about the Multiple Inheritance in Java.

Java LocalDate Class

To compare two LocalDates, LocalTime, and LocalDateTime, Java provides another LocalDate class. It's part of the Java.time package. To compare dates, the class contains isBefore(), isAfter(), isEquals(), and compareTo() methods. These methods work in the same way as the Date and Calendar classes before(), after(), and equals() methods. The dates are checked using the local-time line in all procedures.

of(): It is a static method of the LocalDate class. It takes three int-type parameters: year, month, and date. It gives you a LocalDate with the given date. If any parameter's value is out of range, it throws a DateTimeException.

Syntax:-

public static LocalDate of(int year, int month, int dateOfMonth)  

where,

  • The year must be in the range of MIN_YEAR to MAX_YEAR.
  • The month must be between 1 (January) and 12 (December) (December).
  • The dateOfMonth must be in the range of 1 to 31.

isBefore(): This method determines whether the current date is prior to the supplied date. As an argument, it parses a date (to compare). It only returns true if the date is earlier than the provided date. It uses a different comparison method than compareTo (ChronoLocalDate).

Syntax:-

public boolean isBefore(ChronoLocalDate other)  

isAfter(): This method determines whether the date is before or after the supplied date. As an argument, it parses a date (to compare). It only returns true if the date is earlier than the provided date. It uses a different comparison method than compareTo (ChronoLocalDate).

Syntax:-

public boolean isAfter(ChronoLocalDate other)  

isEqual(): This method compares whether or not the dates are equal. If the dates are equal, true is returned; otherwise, false. As an argument, it parses a date (to compare). It only returns true if the date is earlier than the supplied date.

Syntax:-

public boolean isEqual(ChronoLocalDate other) 

 

Program:-

import java.time.LocalDate;  
public class Main  
{  
    public static void main(String[] args)  
    {  
        // Create LocalDate objects with dates  
        LocalDate d1 = LocalDate.of(2022,9,20);  
        LocalDate d2 = LocalDate.of(2023,11,18);  
         
        System.out.println("Date 1: " + d1);  
        System.out.println("Date 2: " + d2);  
        //comparing two dates  
        if (d1.isAfter(d2))  
        {  
            System.out.println("Date 1 comes after Date 2");  
        }  
        else if (d1.isBefore(d2))  
        {  
            System.out.println("Date 1 comes before Date 2");  
        }  
        else if (d1.isEqual(d2))  
        {  
            System.out.println("Both dates are equal");  
        }  
    }  
}

Output:-

Date 1: 2022-09-20
Date 2: 2023-11-18
Date 1 comes before Date 2

Read More About, Basics of Java

Frequently Asked Questions

What is the return type of compareTo ()?

The Java String class compareTo() method compares the given string with the current string lexicographically. It returns a positive number, negative number, or 0.

What's the difference between the Calendar and Date classes in Java?

The distinction between the Date and Calendar classes is that the Date class deals with a specific point in time, whereas the Calendar class deals with the difference between two dates. The Calendar class allows you to convert between a single point in time and a set of calendar fields like HOUR, YEAR, MONTH, and DAY OF MONTH.

What are the getInstance () methods in the Java calendar class?

The getInstance() method in Java is used to get an instance of a calendar. It is a static method of the Calendar class. This method is used with the calendar object to obtain a calendar instance based on the current time zone defined by the Java Runtime Environment.

Conclusion

In this article, we have extensively discussed the various ways to compare dates in the Java programming language.

Check out this article - Upcasting and Downcasting in Java

We hope this blog has helped you enhance your knowledge regarding comparing dates in Java. If you would like to learn more, check out our articles on the basics of Java and compare versions. Practice makes a man perfect. To practice and improve yourself in the interview, you can check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Java Current Date and time
Next article
Java AWT Basics
Live masterclass