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).