×

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

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

String Handling Method in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

How to convert String to String array in Java

A String in Java is a thing that indicates a collection of letters. We must include the String class from java.lang package if we want to be using strings. An...

5 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

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

Cyclic Barrier in Java

Programmers often find it challenging to run multiple threads simultaneously. Java introduces the idea of concurrency, which enables us to run many threads concurrently, making this work simpler. Concurrent programming...

6 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.