×

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

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

Java Integer reverse() method

The reverse() method of Java Integer class returns the value obtained by reversing the order of the bits in the 2’s complement binary representation. Syntax public static int reverse (int i)  Parameters The parameter...

1 minute read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

Graph Problems in Java

A graph is a special type of data structure used in programming that is made up of edges connecting each set of finitely many nodes, or vertices, to each other....

14 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Java Math addExact() Method

The addExact() method of Math class returns the sum of the two arguments, throwing an exception if the result overflows a long or an int. Syntax public static int addExact (int x,...

1 minute read.

Java Integer class

The Integer class wraps a primitive int type value in an object. Its object contains only a single field whose type is int. Methods: The java.lang.Integer class provides several different methods for...

4 minutes read.

Java Math floorDiv() Method

The floorDiv () method of Math class returns the largest integer value that is less than or equal to the algebraic quotient. It firstly divides the dividend and divisor and...

2 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

Java Applications

The growth in technology is increasing rapidly, so some languages are used for developing them. Java is one such famous programming language which is having numerous applications. The Java Programming...

4 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.