×

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

Related Topics

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes 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 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 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 reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

How to find the length of an Array in Java

Arrays: An array is a sort of container object that stores constant quantities of values of a single type in one memory area. A finite number of items must all be...

3 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

How to write basic Java Programs

Java Basic Programs In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list. To execute a Java program,...

4 minutes read.

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea...

4 minutes read.