How to check Date is Greater in Java?
In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and verifying which one is greater and which one is not.
Introduction
While working on date and time in Java, we occasionally need to analyse dates. Java does not compare dates the same way it compares two numbers. Therefore, it can be a little challenging to compare the two dates with Java. To compare dates, there is no logic to implement. Java offers the compareTo(), before(), after(), as well as equals() methods to make this operation simple. We will discover how to compare and contrast two dates using Java in this part.
In Java, there are four main classes that offer methods for comparing two dates.
- The compareTo() method
- The Date Class
- Class using the calendar
- Use of the LocalDate Class
By CompareTo() Method
The Java Date class offers a variety of time and date-related methods. It belongs to the Java.util class library. The methods Serializable, Cloneable, but also Comparable<Date> are all implemented by the class.
The class offers a compareTo() method for comparing two dates. For ordering, dates are compared. As an argument, it decodes a date that will be compared. Whereas if argument date is null, NullPointerException is thrown.
Its syntax goes as follows
public int compareTo(Date anotherDate)
It offers integer results:
- 0 if the dates are identical.
- Below 0 indicates that the date is earlier than the argument date.
- Whereas if date is greater than the argument date, the value will be larger than 0.
Note: Don't neglect to import java.text when you're using dates in Java. Java.text, SimpleDateFormat Java.util, ParseException Date.
The SimpleDateFormat class, which enables us to accept several date formats, is created as an instance in the example that follows. Following that, we've taken two Date type variables, date1 and date2. We have processed 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 formatted date/time string is returned by the procedure.
We have employed the compareTo() method to compare the two dates. When the dates match, the message "The dates match" is displayed. When the dates match, it prints. The two dates line up. It prints if date1 is higher than date2 Date 1 follows Date 2. It prints if date1 is lower than date2 Date 1 follows Date 2.
Let us implement an example program
File name: CompareDates.java
// Java program that compares the dates by CompareTo() method
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class CompareDates
{
public static void main(String[] args) throws ParseException
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//dates to be compare
Date date1 = sdf.parse("2022-07-28");
Date date2 = sdf.parse("2022-08-16");
System.out.println("Date 1: " + sdf.format(date1));
System.out.println("Date 2: " + sdf.format(date2));
// comparable dates
if(date1.compareTo(date2) > 0)
{
System.out.println("Date 1 comes after Date 2");
}
else if(date1.compareTo(date2) < 0)
{
System.out.println("Date 1 comes before Date 2");
}
else if(date1.compareTo(date2) == 0)
{
System.out.println("Both dates are equal");
}
}
}
Output
Date 1: 2022-07-28
Date 2: 2022-08-16
Date 1 comes before Date 2
The Date Class
To analyse dates, the Java date class has the before(), after(), and equals() methods.
before(): The technique determines whether the date falls on or before the provided date. It parses a date-type parameter. If and only if the time instant defined by such a Date object is precisely earlier than the time instant described by when, it returns true; otherwise, it returns false.
Its syntax would be as follows
public boolean before(Date when)
If when is null, it raises a NullPointerException.
after(): The technique determines whether the date falls on or after the specified date. It parses a date-type parameter. If and only if the time instant reflected through this Date object is precisely later than the time instant described by when, it returns true; otherwise, it returns false.
Its syntax would be as follows
public boolean after(Date when)
If when is null, it raises a NullPointerException.
equals(): The procedure compares and verifies that two dates are equal. The Object class's equals() method is overridden. Whereas if objects are identical, it returns true; if not, it returns false. As a result, the Date objects only become identical if both dates' getTime() returns a same long value.
Its syntax would be as follows
public boolean equals (Object obj)
Let us understand it by implementing an example program
File name: CompareDates2.java
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class CompareDates2
{
public static void main(String args[]) throws ParseException
{
SimpleDateFormat sdfo = new SimpleDateFormat("yyyy-MM-dd");
//dates to be compared
Date date1 = sdfo.parse("2022-08-16");
Date date2 = sdfo.parse("2022-08-25");
System.out.println("Date1: " + sdfo.format(date1));
System.out.println("Date2: " + sdfo.format(date2));
// Check out the two dates.
if (date1.after(date2))
{
// if date1 > date2, print the next sentence.
System.out.println("Date1 comes after Date2");
}
else if (date1.before(date2))
{
// if date1 > date2, print the next sentence.
System.out.println("Date1 comes before Date2");
}
else if (date1.equals(date2))
{
// The phrase "date1=date2" is printed.
System.out.println("Both dates are equal");
}
}
}
Output
Date1: 2022-08-16
Date2: 2022-08-25
Date1 comes before Date2
Class Using the Calendar
The Calendar class offers the before(), after(), as well as equals() methods similar to what the Java Date class does. As we have already stated, all three techniques have the same signature.
Let's compare two dates using the after(), before(), or even equals() methods of the Calendar class.
With the exception of the getInstance() as well as setTime() methods, the method employed in the preceding example is the identical in the example that follows.
getInstance(): This is a static Calendar method. The standard time zone and region are used when returning a Calendar.
Its syntax would be as follows
public static Calendar getInstance()
setTime(): The technique adjusts the calendar time to the given date. It parses a date-type parameter.
Its syntax would be as follows
public final void setTime(Date date)
Let us understand it by implementing an example program
File name: CompareDates3.java
import java.util.Date;
import java.util.Calendar;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class CompareDates3
{
public static void main(String args[]) throws ParseException
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// date comparisons
Date date1 = sdf.parse("2020-12-01");
Date date2 = sdf.parse("2020-12-01");
System.out.println("Date1: " + sdf.format(date1));
System.out.println("Date2: " + sdf.format(date2));
// invoking getInstance() method
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
// contrasting two dates
if (cal1.after(cal2))
{
//if date1 greater than date2
System.out.println("Date1 comes after Date2");
}
else if (cal1.before(cal2))
{
//if date1<date2
System.out.println("Date1 comes before Date2");
}
else if (cal1.equals(cal2))
{
//if date1=date2
System.out.println("Both dates are equal");
}
}
}
Output
Date1: 2020-12-01
Date2: 2020-12-01
Both dates are equal
Use of LocalDate Class
To consider two LocalDate, LocalTime, as well as LocalDateTime, Java offers an additional LocalDate class. It belongs to the java.time package. To compare dates, the class has the isBefore(), isAfter(), isEquals(), or compareTo() methods. The before(), after(), the equals() methods of both the Date and the Calendar class are functionally equivalent to these methods
Let's compare two dates using an example using the LocalDate class.
The technique used to compare the two dates is shown in the example below. The dates are verified using each method's local time line.
of(): It belongs to the LocalDate class and is static. It gets a LocalDate instance from the year, month, including day. It accepts three int-typed parameters: year, month, and date. It provides a LocalDate only with requested date in it.
Its syntax would be as follows
public static LocalDate of(int year, int month, int dayOfMonth)
If any parameter's value is outside of the acceptable range, it raises a DateTimeException.
isBefore(): The technique verifies that the date is earlier than the target date. It reads the input 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).
Its syntax would be as follows
public boolean isBefore(ChronoLocalDate other)
isAfter(): The approach makes sure the date is earlier than the target date. As an argument, it evaluates a date for comparison. Only when the date is earlier than the desired date will it return true. Its comparing methodology differs from compareTo's (ChronoLocalDate).
Its syntax would be as follows
public boolean isAfter(ChronoLocalDate other)
isEqual(): The approach determines whether or not the dates are equal. It returns true if the two dates are equivalent and false otherwise. It processes the request a date as a parameter (for comparison).
Only in the event that the date is earlier than the target date, it returns true. It uses a different comparison methodology than compareTo (ChronoLocalDate).
public boolean isEqual(ChronoLocalDate other)
Let us understand it with an example program
File name: CompareDates4.java
import java.time.LocalDate;
public class CompareDatesExample4
{
public static void main(String[] args)
{
// Dates can be created as LocalDate objects.
LocalDate date1 = LocalDate.of(2022,09,23);
LocalDate date2 = LocalDate.of(2022,10,23);
System.out.println("Date1: " + date1);
System.out.println("Date2: " + date2);
// two dates are contrasted.
if (date1.isAfter(date2))
{
System.out.println("Date1 comes after Date2");
}
else if (date1.isBefore(date2))
{
System.out.println("Date1 comes before Date2");
}
else if (date1.isEqual(date2))
{
System.out.println("Both dates are equal");
}
}
}
Output
Date1: 2022-09-23
Date2: 2022-10-23
Date1 comes before Date2