How to compare two dates in Java?

JavaObject Oriented ProgrammingProgramming

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

Syntax

int compareTo(T o)

Example

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");
      Date d1 = sdformat.parse("2019-04-15");
      Date d2 = sdformat.parse("2019-08-10");
      System.out.println("The date 1 is: " + sdformat.format(d1));
      System.out.println("The date 2 is: " + sdformat.format(d2));
      if(d1.compareTo(d2) > 0) {
         System.out.println("Date 1 occurs after Date 2");
      } else if(d1.compareTo(d2) < 0) {
         System.out.println("Date 1 occurs before Date 2");
      } else if(d1.compareTo(d2) == 0) {
         System.out.println("Both dates are equal");
      }
   }
}

In the above example, the date d1 occurs before the date d2, so it can display "Date 1 occurs before Date 2" in the console.

Output

The date 1 is: 2019-04-15
The date 2 is: 2019-08-10
Date 1 occurs before Date 2
raja
Published on 03-Sep-2019 11:58:18
Advertisements