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


This program compares two different dates using the compareTo() 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 program then compares date1 and date2 using the compareTo() method, which returns an integer value. If the value is greater than 0, it means that date1 is later than date2. If the value is less than 0, it means that date2 is later than date1. If the value is 0, it means that both dates are equal. In this case, since date1 is later than date2, the output will be "Date 1 is Later than Date 2".

Source Code

import java.util.*;
public class DateCompareTo_Method
{
	public static void main(String[] args)
	{
		Date date1 = new Date(21, 12, 07);
		Date date2 = new Date(20, 10, 15);
		// Date date2 = new Date(21, 12, 07);
 
		int res = 0;
 
		res = date1.compareTo(date2);
		if (res > 0)
		{
			System.out.println("Date 1 is Later than Date 2");
		}
		else if (res < 0)
		{
			System.out.println("Date 2 is Later than Date 1");
		}
		else
		{
			System.out.println("Both are Equal");
		}		
	}
}

Output

Date 1 is Later than Date 2

Example Programs