Write a Java Program to Compare dates using the Date.equals() method


This program compares three different dates using the equals() method of the Date class. The first Date object date1 is initialized to December 7th, 2021. The second Date object date2 is initialized to October 15th, 1920. The third Date object date3 is initialized to December 7th, 2021, which is the same as date1.

The program then compares date1 and date2 using the equals() method, and since they represent different dates, the output will be "Date 1 and Date 2 are Not Equal". The program then compares date2 and date3 using the equals() method, and since they represent the same date, the output will be "Both are Equal".

Source Code

import java.util.*;
public class DateEquals_Method
{
	public static void main(String[] args)
	{
		Date date1 = new Date(21, 12, 07);
		Date date2 = new Date(20, 10, 15);
		Date date3 = new Date(21, 12, 07);
 
		boolean res;
 
		res = date1.equals(date2);
		if (res == true)
		{
			System.out.println("Both are Equal");
		}
		else
		{
			System.out.println("Date 1 and Date 2 are Not Equal");
		}
 
		res = date2.equals(date3);
		if (res == true)
		{
			System.out.println("Both are Equal");
		}
		else
		{
			System.out.println("Date 2 and Date 3 are Not Equal");
		}
	}
}

Output

Date 1 and Date 2 are Not Equal
Date 2 and Date 3 are Not Equal

Example Programs