×

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

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Java CountDownLatch

Another crucial classes for concurrent execution is CountDownLatch. It is a synchronisation tool that enables one or more threads to await until a series of tasks started by another thread...

4 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Java file Reader

File Reader: It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file. Input Stream: Java.io...

4 minutes 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.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Java array list remove time complexity

Java: We know that java is one of the programming languages. The main feature of java which is not in C or object oriented programming language is platform independence. Not only the...

7 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.