Java Program to Compare Dates Using Date.CompareTo() Method

You are currently viewing Java Program to Compare Dates Using Date.CompareTo() Method

Java program to compare dates using Date.compareTo() method

// Java program to compare dates using 
// Date.compareTo() 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);

    int result = 0;

    result = date1.compareTo(date2);
    if (result > 0)
      System.out.println("The date1 is later than date2");
    else if (result < 0)
      System.out.println("The date2 is later than date1");
    else
      System.out.println("Both are equal");

    result = date2.compareTo(date3);
    if (result > 0)
      System.out.println("The date2 is later than date3");
    else if (result < 0)
      System.out.println("The date3 is later than date2");
    else
      System.out.println("Both are equal");
  }
}

Output

The date1 is later than date2
Both are equal

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply