In Java, there is often a need to compare the dates while dealing with date and time. This comparison is not like comparing the numbers and is much needed when comparing multiple dates close to one another. In such a situation, the Java methods and classes are useful in comparing the dates based on the time or with respect to the current Date.
How to Compare Dates in Java?
In Java, dates can be compared via the following approaches:
- “compareTo()” Method.
- “Date” Class.
- “Calendar” Class.
- “LocalDate” Class.
What is the Difference Between the “Date” Class, “Calendar” Class, and “LocalDate” Class?
The “Date” class is outdated and handles a specific point in time. The “Calendar” class, however, deals with the difference between the dates and enables conversion between a single time point and calendar fields i.e., year, month, etc.
The “LocaleDate” class represents a date without time or timezone information and is suitable for the dates only. It represents the date in ISO format i.e., (yyyy-MM-dd) without time.
How to Use Date Comparison Methods in Java?
Below are the common methods used in the Date comparison approaches:
compareTo(): This method compares the two strings where the comparison is based on each character’s Unicode value.
Syntax
public int compareTo(String st)
public int compareTo(Object ob)
In these syntaxes, “st” and “ob” point to the other string or object to be compared.
Return Value
This method returns “0” if both the compared strings are equal, “<0” if the associated date is less than the specified date, and “>0” if the pointed date is greater than the specified date.
“Date” Class Methods
Method | Description | Syntax | Return Value |
Date.before() | It checks/analyzes if the given date is before the other specified date. | before(Date dat) | It returns true if the associated date is before the date passed as an argument. |
Date.after() | It verifies if the given date is after the passed argument date. | after(Date dat) | It returns true if the associated date is after the date passed as an argument. |
Date.equals() | It checks if the given date equals the other specified date. | equals(Date dat) | It returns true if the associated date equals the date passed as the argument. |
Note: In the above syntaxes, “dat” refers to the date to be compared with.
“Calendar” Class Methods
Method | Description | Syntax | Return Value |
Calendar.before() | This method checks if the time represented by this(associated) calendar is before the time represented by the specified instance. | public boolean before(Object x) | It returns true if the time represented by the associated Calendar is before the specified time. |
Calendar.after() | It analyzes if the time represented via the associated calendar is after the represented time by the specified instance. | public boolean after(Object x) | It returns true if the time represented by the associated Calendar is after the specified time. |
Calendar.equals() | It checks if the time represented by the linked calendar equals the time represented by the specified instance. | public boolean equals(Object x) | It returns true if the time represented by the associated Calendar equals the specified time. |
getInstance() | This static method gives the Calendar utilizing the default time zone and locale. | public static Calendar getInstance() | It returns a Calendar |
setTime() | It sets the calendar time based on the given date. | public final void setTime(Date d) Here, “d” refers to the date to be set. | This method does not return any value. |
Note: In the syntaxes, “x” represents the Calendar instance to be compared with.
“LocalDate” Class Methods
Method | Description | Syntax | Return Value |
isBefore() | This method analyzes if the date is before the date specified as an argument. | public boolean isBefore(ChronoLocalDate x) | This method returns “true” if the associated date is before the specified date. |
isAfter() | It checks if this date comes after the date passed as an argument. | public boolean isAfter(ChronoLocalDate x) | This method returns “true” if this date comes after the specified date. |
isEqual() | This method analyzes if this date equals the specified date. | public boolean isEqual(ChronoLocalDate x) | This method returns “true” if this date equals the specified date. |
Note: In the above-given syntaxes, “x” represents the date to be compared to, not null.
Approach 1: Compare Dates in Java Using the “compareTo()” Method
The dates can be compared by this particular method using the “if/else” conditional statements or evaluating the results based on the method’s return type:
package jbArticles;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class Datecompare {
public static void main(String[] args) throws ParseException {
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = dt.parse("2023-11-29");
Date date2 = dt.parse("2023-12-15");
System.out.println("Date 1 -> " + dt.format(date1));
System.out.println("Date 2 -> " + dt.format(date2));
if(date1.compareTo(date2) < 0) {
System.out.println("Date 1 is before Date 2");
}
else if(date1.compareTo(date2) > 0) {
System.out.println("Date 1 is after Date 2");
}
else if(date1.compareTo(date2) == 0) {
System.out.println("Both dates are equal");
}
}}
Code Explanation
- First, import the specified libraries to use the “Date”, and “SimpleDateFormat” classes and declare the “parseException” exception, respectively.
- Create a “SimpleDateFormat” instance and initialize it with the “yyyy-MM-dd” format.
- After that, use the “parse()” method to specify the dates according to the specified format and display the dates.
- Now, apply the “compareTo()” method to compare both the specific dates using the “if/else” conditional statements.
- Finally, print the corresponding result based on the comparison.
Output
In this output, it can be seen that the comparison of dates is done appropriately.
Alternatively, specify the following code line instead of the “if/else” statement that returns the “compareTo()” method’s return value:
System.out.println(date1.compareTo(date2));
Output
This returned value implies that the first date comes before the second date.
Approach 2: Compare Dates in Java Using the “Date” Class
The “Date” class methods can also be used to compare the dates that return the corresponding boolean values based on comparisons:
package jbArticles;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class Datecompare {
public static void main(String[] args) throws ParseException {
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = dt.parse("2023-10-29");
Date date2 = dt.parse("2023-09-15");
System.out.println("Date 1 -> " + dt.format(date1));
System.out.println("Date 2 -> " + dt.format(date2));
System.out.println("Is Date 1 before Date 2? " +date1.before(date2));
System.out.println("Is Date 1 after Date 2? " +date1.after(date2));
System.out.println("Is Date 1 equal to Date 2? " +date1.equals(date2));
}}
Code Explanation
First, specify the dates to be compared using the “SimpleDateFormat” instance, parse, and display the dates. After that, use the Date class “before()”, “after()” and “equals()” methods to compare both the dates accordingly.
Output
From this output, it can be said that the first specified date comes after the second date.
Important Consideration
The Date can also be specified in a short form rather than the exact format. It is due to the fact that it is automatically parsed with the “0’s” and the result is returned appropriately, as demonstrated below:
Approach 3: Compare Dates in Java Using the “Calendar” Class
This approach makes use of the Calendar class’s “Calendar.before()”, “Calendar.equals()”, and “Calendar.after()” methods to compare the dates based on the time represented by the calendars:
package jbArticles;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Calendar;
public class Datecompare {
public static void main(String[] args) throws ParseException {
SimpleDateFormat dt = new SimpleDateFormat("yyyy-mm-dd");
Date date1 = dt.parse("2023-15-09");
Date date2 = dt.parse("2023-15-09");
System.out.println("Date 1 -> " + dt.format(date1));
System.out.println("Date 2 -> " + dt.format(date2));
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(date1);
c2.setTime(date2);
System.out.println(c1.before(c2));
System.out.println(c1.after(c2));
System.out.println(c1.equals(c2));
}}
Code Explanation
- Create an object of the “SimpleDateFormat” class containing the given format, specify the dates to be compared accordingly, and display them.
- Now, use the “getInstance()” method to initialize the Calendar class objects.
- Apply the “setTime()” method to assign the Date values to the Calendar objects.
- Lastly, use the “before()”, “after()” and “equals()” methods, respectively to compare both the dates.
Output
Here, it can be implied that both the dates are equal therefore, the corresponding boolean value “true” is returned by the “equals()” method.
Approach 4: Compare Dates in Java Using the “LocaleDate” Class
The “LocalDate” class “isBefore()”, “isAfter()”, and “isEqual()” methods can also be used to compare the specified date with the current date using the “if/else” statements:
package jbArticles;
import java.time.LocalDate;
import java.text.ParseException;
public class Datecompare {
public static void main(String[] args) throws ParseException {
LocalDate date1 = LocalDate.of(2023,11,29);
LocalDate date2 = LocalDate.now();
System.out.println("Date 1 -> " + date1);
System.out.println("Date 2 -> " + date2);
if (date1.isAfter(date2)) {
System.out.println("Date1 is after Date2");
}
else if (date1.isBefore(date2)) {
System.out.println("Date1 is before Date2");
}
else if (date1.isEqual(date2)) {
System.out.println("Both dates are equal");
}
}}
Code Explanation
- Create “LocalDate” instances such that the first instance contains the specified date.
- The second instance, however, represents the current date via the “now()” method. After that, display both dates.
- Now, use the “isAfter()”, “isBefore()” and “isEqual()” methods to check if the first date is after, before, or equal to the second i.e., current date.
- The “if/else” statements then log the corresponding condition based on the comparison.
Output
This output signifies that both dates are equal since the first date is specified as the current date.
Conclusion
In Java, the dates can be compared using the “compareTo()” method, the “Date” class, the “Calendar” class, or via the “LocalDate” class. These approaches compare the dates based on the specified format, fetched time, or based on the current date. The comparison can be analyzed via the method’s return types, custom-applied “if/else” conditional statements, or the returned boolean values.