×

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore, comparing the two dates using Java can take much work. To compare the dates, there is no logic to implement. Java offers the compareTo(), before(), after(), & equals() methods to make this operation simple. In this part, we will study how and where to compare and contrast the two dates using Java.

Java has four classes that offer methods for comparing two dates.

  • Using the method compareTo() 
  • Utilizing the Date class 
  • Utilizing the Calendar Classes
  • Applying the LocalDate Class

Using the method compareTo()

The Java Date class offers a variety of time and date-related methods. It belongs to the Java.util class library. The class complies with the interfaces Comparable, Cloneable, and SerializableDate>.

The class offers a compareTo() method for comparing two dates. For orders, dates are compared. As an argument, it decodes a date that will be compared. If an argument date is null, NullPointerException is thrown.

Syntax:

int public compareTo (Date anotherDate)

It returns the values of integer:

  • 0 if the dates are identical.
  • Less than 0 indicates that the date is earlier than the argument date.
  • If the date is later than the argument date, the value will be greater than 0.

Always remember to import Java.text when working with dates in Java. Java.text, SimpleDateFormat Java.util.Date ParseException

Let's compare two dates using the compareTo() method.

The SimpleDateFormat class, which enables us to accept several date formats, is created as an instance in the following example. Following that, we've taken two Date type variables, date1, and date2. We then parsed the dates to compare using the parse() function of the SimpleDateFormat class. From the string, the procedure extracts a date that is returned. Date variables of types date1 and date2 were provided to the format() method. The procedure returns the formatted date/time string.

We have employed the compareTo() method to compare the two dates. When the dates match, it prints. The two dates line up. It prints when the date1 is greater than the date2 Date 1 follows Date 2. It prints when the date1 gets smaller than the date2 Date 1 follows Date 2.

CompareDatesDemo1.java

import java.util.Date;  
import java.text.TheSimpleDateFormat;  
import java.text.ParseException;  
public class CompareDatesDemo1 
{  
public static void main(String[] args) throws ParseException   
{  
// TheSimpleDateFormat class object
TheSimpleDateFormat srj = new TheSimpleDateFormat("yyyy-MM-dd");  
// date comparisons
Date date3 = srj.parse("2019-11-18"); 
Date date1 = srj.parse("2019-10-16"); 
//date is printed here  
System.out.println("Date 3: " + srj.format(date3));  
System.out.println("Date 1: " + srj.format(date1));  
//comparison of the dates  
if(date3.compareTo(date3) > 0)   
{  
System.out.println("Date 3 follows Date 1");  
}   
else if(date3.compareTo(date1) < 0)   
{  
System.out.println("Date 3 precedes Date 1");  
}   
else if(date3.compareTo(date1) == 0)   
{  
System.out.println("Both the dates match each other. ");  
}  
}  
}  

Output:

Date 3: 2019-11-18
Date 1: 2019-10-16
Date 3 follows Date 1

Utilizing the Date class

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

before(): This function determines whether the current date is earlier than the supplied date. It parses a date-type parameter. If and only if the time instant indicated through this Date object was absolutely earlier than the time instant described by when it returns true; otherwise, it returns false.

Syntax:

public boolean previous(Date when)

If when it is null, it raises a NullPointerException.

after(): This function determines if the current date falls on or after the supplied date. It parses a date-type parameter. If and only if the time instant represented by this Date object is strictly later than the time instant represented by when it returns true; otherwise, it returns false.

Syntax:

public Boolean later(Date when)

If when it is null, it raises a NullPointerException.

equals(): This function determines whether two dates are equal (compares). It overrides the Object class's equals() method. If objects are the same, it returns true; otherwise, it returns false. The getTime() method must return the same long number for both dates for the Date objects to be equal.

Syntax:

public boolean equals(Object objt)  

Let's compare two dates using the methods described above using the example provided above.

CompareDatesDemo3.java

import java.util.Dates;   
import java.text.ParseException;   
import java.text.TheSimpleDateFormat;   
public class CompareDatesDemo3  
{   
public static void main(String args[]) throws ParseException   
{   
// Making one object of the class SimpleDateFormat
TheSimpleDateFormat srj = new TheSimpleDateFormat("yyyy-MM-dd");   
//comparison of the dates    
Date date3 = srj.parse("2018-02-02");   
Date date1 = srj.parse("2019-02-02");   
// dates are printed here   
System.out.println("Date3: " + srj.format(date3));   
System.out.println("Date1: " + srj.format(date1));   
//two dates comparision 
if (date3.after(date1))   
{   
//if date3>date2, following statement is printed 
System.out.println("Date1 is followed by Date3");   
}  
else if (date3.before(date1))   
{   
//if date3<date1, following statement is printed here   
System.out.println("Date3 precedes Date1");   
}   
else if (date3.equals(date1))   
{   
//date3=date1 following statement is printed  
System.out.println("Both of the dates are same");   
}   
}   
}  

Output:

Date3: 2018-02-02
Date1: 2019-02-02
Date3 precedes Date1

Making Use of the Calendar

The Calendar class has equals(), before(), and after() methods the same as the Java Date class does. The foregoing explanation explains that all three techniques have the same signature.

With the aid of the after(), before(), and equals() methods, let's compare two dates using the Calendar class.

The getInstance() and setTime() techniques have been left out of the next example, which uses the same method as the previous one.

The static method of a Calendar is called getInstance(). With the standard time zone and locale, it returns a Calendar.

Syntax:

public static Calendars getInstance()  

CompareDatesDemo4.java

import java.util.Dates;   
import java.util.Calendars;   
import java.text.ParseException;   
import java.text.TheSimpleDateFormat;   
public class CompareDatesDemo4 
{   
public static void main(String args[]) throws ParseException   
{   
// TheSimpleDateFormat object creation
TheSimpleDateFormat srj = new TheSimpleDateFormat("yyyy-MM-dd");   
// comparision of the dates  
Date date3 = srj.parse("20219-11-02");   
Date date1 = srj.parse("2019-11-02");   
// dates are printed here   
System.out.println("Date3: " + srj.format(date3));   
System.out.println("Date1: " + srj.format(date1));   
// executing the function getInstance()
Calendars cale3 = Calendars.getInstance();   
Calendars cale1 = Calendars.getInstance();   
cale3.setTime(date3);   
cale1.setTime(date1);   
//dates are compared here   
if (cale3.later(cale1))   
{   
//if the dates date3>date1   
System.out.println("Date1 is followed by Date3");   
}   
else if (cale3.prev(cale1))   
{   
//if the dates date3<date1  
System.out.println("Date3 precedes Date1.");   
}   
else if (cal3.equals(cal1))   
{   
//if the dates date3=date1  
System.out.println("the dates are same for both");   
}   
}   
}

Output:

Date3: 2019-11-02
Date1: 2019-11-02
the dates are same for both

Applying the LocalDate Class

Another LocalDate class for comparing these two LocalDate, LocalTime, and the LocalDateTime is provided by Java. It is a component of the Java.time package. Date comparison can be done using the class's isBefore(), isAfter(), isEquals(), as well as compareTo() methods. Similar to the before(), after(), and equals() methods of the Date and Calendar class, these methods also function.

Let's compare two dates using the LocalDate class as an example.

In the example below, we compared two dates using the technique listed below. Each method verifies the dates using the local time line.

of(): The class LocalDate's static method. It obtains a LocalDate object based on the day, month, and year. Three int-type parameters are accepted: year, month, and date. It gives back a LocalDate with requested date.

Syntax:

public static TheLocalDate of(int yr, int mnt, int dayOfTheMonth)

where:

yr: Must fall within the range of MIN YEAR and MAX YEAR.

Mnt: must fall within the range of 1 (January) and 12 (December).

datOfTheMonth: must be in the range of 1 to 31.

If any parameter's value is outside of the acceptable range, it throws a DateTimeException.

isBefore() verifies whether the current date is earlier than the target date. That parses a date as a parameter (for comparison). But only when the date is earlier than the target date, it returns true. It uses a different comparison methodology than compareTo (ChronoLocalDate).

Syntax:

public boolean isBefore(TheChronoLocalDate other) 

isAfter(): This function determines if the current date is earlier than the target date. It decodes a date as a parameter (for comparison). If and only if the date comes earlier than the target date, it returns true. It uses a different comparison methodology than compareTo (ChronoLocalDate).

Syntax:

public boolean isAfter(TheChronoLocalDate other) 

isEqual(): compares whether two dates are equal. It returns true if the two dates are equivalent and false otherwise. It reads the input a date as a parameter (for comparison).

If and only if the date comes earlier than the target date, it returns true. It uses a different comparison methodology than compareTo (ChronoLocalDate).


Related Topics

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

How to Convert String to char in Java

How to Convert String to char in Java There are two methods to convert String to char are: Using charAt() method Using tocharArray() method Using charAt() method This is the method of String class that...

3 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.