×

Java Programs

Java Practice

Java program to compare dates using the Date.equals() method

Learn how to compare dates using the Date.equals() method in Java?
Submitted by Nidhi, on March 31, 2022

Problem statement

Given two dates, we have to compare them, create objects of the Date class with specified dates and then compare dates using the Date.equals() method.

The equals() method returns Boolean value. If both date object has the same value then it returns true, otherwise, it returns false.

Java program to compare dates using the Date.equals() method

The source code to compare dates using Date.equals() method is given below. The given program is compiled and executed successfully.

// Java program to compare dates using 
// Date.equals() method

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Date date1 = new Date(22, 9, 16);
    Date date2 = new Date(21, 10, 15);
    Date date3 = new Date(21, 10, 15);

    boolean result;

    result = date1.equals(date2);
    if (result == true)
      System.out.println("Both are equal");
    else
      System.out.println("The date1 and date2 are not equal");

    result = date2.equals(date3);
    if (result == true)
      System.out.println("Both are equal");
    else
      System.out.println("The date2 and date3 are not equal");
  }
}

Output

The date1 and date2 are not equal
Both are equal

Explanation

In the above program, we imported the "java.util.*" package to use the Date class. Here, we created a class Main that contains a static method main(). The main() method is the entry point for the program, here we created three objects of the Date class with specified dates. Then we compared created objects using the equals() method and printed appropriate messages.

Java Date and Time Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.