×

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if date1 is after date2, and returns a price "an awful lot less than zero" if date1 is earlier than date2.

The Date elegance represents a particular on-the-spot in time, with millisecond precision. It provides constructors and strategies to address date and time with Java. To make this challenge easy Java affords compareTo(), before(), after(), and equals() method. In this segment, we will learn how to compare dates in Java, there are four instructions.

For compare dates in java, there are four classes. These are:

  1. Using compareTo() Method
  2. Using LocalDate Class Method
  3. Using Date Class Method
  4. Using Calendar Class Method

Using compareTo() Method: We can use Date.compareTo() method by using some simple steps-

  1. At first, create an object of simple date format.
  2. Initializing the date format like yyyy-mm-dd.
  3. After that, initialize some variables in the date mentioned above format (yyyy-mm-dd) Then examine dates using the compareTo() approach.
  4. When the process mentioned above is completed, then we print the result.

Using after(), before() and equals() Method: We can use Date.after(), Date.before() and Date.equals() method by using some simple step-

  1. At first, create an object of simple date format.
  2. Initializing the date format like yyyy-mm-dd.
  3. After that, initialize some variables in the date as mentioned above format (yyyy-mm-dd) Then compare two dates using date.after(), Date.before(), Date.equals() method.
  4. When the process mentioned above is completed, then we print the result.

Using calender.after(), calender.before() and calender.equals() Method: We can use Calendar.after(), Calender.before() and Calender.equals() method by using some simple step-

  1. At first, create an object of simple date format.
  2.  Initializing the date format like yyyy-mm-dd.
  3. After that, initialize some variables in the date as mentioned above format (yyyy-mm-dd). Initialize the Calendar class objects the usage of the get instance() functions.
  4. The time() function of Calendar magnificence assigns the values to the calendar items.
  5. Use after() and before features of the Calendar elegance for the comparisons of dates When the process mentioned above is completed, we print the result.

Syntax of Date.compareTo() method in Java: Every function have some syntax. So, In Java, the Date.compareTo() method has a syntax.

public int compare To (Date another Date)

Returns value: The Date.compareTo() method can return some integer values like 0, less than 0 and greater than 0.

When both the dates are equal, this function returns the value 0. When the date is before the date of argument, then this function returns a value which is less than 0.

When the date is after the date of argument, this function returns a value greater than 0.

Note: Whilst copying the date in Java, take into account to import Java. text.SimpleDateFormat, java.text.ParseException, java.util.Date. allow implement the compareTo() technique and compares two dates.

Within the following example, we've created an example of the SimpleDateFormat elegance that allows us to take different date codecs. After that, we have taken variables, date1, and date2, of kind Date. the use of the parse() technique of the SimpleDateFormat class, we've got parsed the dates to examine. We've got handed the date1 and date2 variables of type date inside the layout() manner.

The method offers the formatted date string or time string. We've used the compareTo() technique to compare the two dates. If both dates are identical, it prints both dates are equal.

Then it returns the value 0. If the date1 is extra than the date2 then it prints Date 1 comes after Date 2. It means, When the date is before the date of argument, this function returns the value which is less than 0, and when the date is after the date of argument, then this function returns the value which is greater than 0.

Example 1: Right here, we supply an instance of the use of the Date.compareTo() technique in Java.

import java.text.*;
import java.util.Date;
public class CompareTwoDatesTest
{
public static void main (String[] args) throws ParseException
{
SimpleDateFormat sdformat = new SimpleDateFormat (“yyyy-mm-dd”);
// the dates initialize
Date d1 = sdformat . parse (“2022-09-08”);
Date d2 = sdformat . parse (“2022-09-08”);
//Print the dates
System.out.println (“The date 1 is : ” + sdformat . format (d1));
System.out.println (“The date 2 is : ” + sdformat . format (d2));
//Compare the dates
if (d1 . compareTo(d2) < 0)
{
System.out.println (“Date 1 is occurs before Date 2”);
}
else if (d1 . compareTo(d2) > 0)
{
System.out.println (“Date 1 is occurs after Date 2”);
}
else if (d1 . compareTo(d2) == 0)
{
System.out.println (“Date 1 and Date 2 both dates are equal”);
}
}
}

Output: We will compile the program and also run it. After the execution, the result is equal to 0. Because date 1 is equal to date 2.

The date 1 is : 2022-09-08
The date 1 is : 2022-09-08
Date 1 and Date 2 both dates are equal

Example 2: Right here, we supply an instance of the use of the Date.compareTo() technique in Java.

\import java.text.*;
import java.util.Date;
public class CompareTwoDatesTest
{
public static void main (String[] args) throws ParseException
{
SimpleDateFormat sdformat = new SimpleDateFormat (“yyyy-mm-dd”);
//the dates initialize
Date d1 = sdformat . parse (“2022-09-08”);
Date d2 = sdformat . parse (“2022-09-20”);
//Print the dates
System.out.println (“The date 1 is : ” + sdformat . format (d1));
System.out.println (“The date 2 is : ” + sdformat . format (d2));
//Compare the dates
if (d1 . compareTo(d2) < 0)
{
System.out.println (“Date 1 is occurs before Date 2”);
}
else if (d1 . compareTo(d2) > 0)
{
System.out.println (“Date 1 is occurs after Date 2”);
}
else if (d1 . compareTo(d2) == 0)
{
System.out.println (“Date 1 and Date 2 both dates are equal”);
}
}
}

Output: We will compile the program and also run it. After the execution, the result is less than 0. Because date 1 occurs before date 2.

The date 1 is: 2022-09-08
The date 1 is: 2022-09-20
Date 1 is occurs before Date 2

Example 3: Right here, we supply an instance of the use of the Date.compareTo() technique in Java.

import java.text.*;
import java.util.Date;
public class CompareTwoDatesTest
{
public static void main (String[] args) throws ParseException
{
SimpleDateFormat sdformat = new SimpleDateFormat (“yyyy-mm-dd”);
//the dates initialize
Date d1 = sdformat . parse (“2022-09-10”);
Date d2 = sdformat . parse (“2022-09-02”);
//Print the dates
System.out.println (“The date 1 is : ” + sdformat . format (d1));
System.out.println (“The date 2 is : ” + sdformat . format (d2));
//Compare the dates
if (d1 . compareTo(d2) < 0)
{
System.out.println (“Date 1 is occurs before Date 2”);
}
else if (d1 . compareTo(d2) > 0)
{
System.out.println (“Date 1 is occurs after Date 2”);
}
else if (d1 . compareTo(d2) == 0)
{
System.out.println (“Date 1 and Date 2 both dates are equal”);
}
}
}

Output: We will compile the program and also run it. After the execution, the result is greater than 0. Because date 1 occurs after date 2.

The date 1 is: 2022-09-10
The date 1 is: 2022-09-02
Date 1 is occurs after Date 2

Example 4: Right here, we supply an instance of the use of the Date.compareTo() technique in Java. For the use of Java.util.Calendar, the Calendar works a similar way as Java.util.Date. And the Calendar incorporates the similar compareTo, before(), after() and equals() to evaluate calendar.

import java.test.SimpleDateFormat;
import java.util.Calender;
import java.util.ParseException;
import java.util.Date;
public class CompareCalender
{
public static void main (String[] args) throws ParseException
{
SimpleDateFormat sdformat = new SimpleDateFormat (“yyyy-mm-dd”);
//the dates initialize
Date d1 = sdformat . parse (“2022-09-10”);
Date d2 = sdformat . parse (“2022-08-20”);
Calendar cal1 = Calender.getInstance();
Calendar cal2 = Calender.getInstance();
Cal1.setTime(date1);
Cal2.setTime(date2);




//Print the dates
System.out.println (“The date 1 is : ” + sdformat . format (d1));
System.out.println (“The date 2 is : ” + sdformat . format (d2));
//Compare the dates
if (cal1 . before (cal2))
{
System.out.println (“Date 1 is occurs before Date 2”);
}
else if (cal1 . after (cal2))
{
System.out.println (“Date 1 is occurs after Date 2”);
}
else if (cal1 . equals (cal2))
{
System.out.println (“Date 1 and Date 2 both dates are equal”);
}
}
}

Output: We will compile the program and also run it. After the execution, the result is greater than 0. Because date 1 occurs after date 2.

The date 1 is: 2022-09-10
The date 1 is: 2022-08-20
Date 1 is occurs after Date 2

So, here we give some examples of the use of the compareTo() technique. We write the program and also share the output of the assigned programs.


Related Topics

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

Hogben Numbers in Java

In this section, we will discover what the Hogben number is and develop Java programs that compute it. Java coding interviews and academic exams typically involve questions about the Hogben...

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

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.

What are Array strings in Java?

In normal programming, An array is a group and a collection of identical forms of data that are stored in a sequential memory region and may be accessed using their...

4 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

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

7 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.