Java Program to Match Dates


Firstly, we have considered the following two dates.

SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = s.parse("2018-10-15");
Date d2 = s.parse("2018-11-10");

Now, use the compareTo() method to compare both the dates. The results are displayed on the basis of the return value.

if (d1.compareTo(d2) > 0) {
   System.out.println("Date1 is after Date2!");
   } else if (d1.compareTo(d2) < 0) {
      System.out.println("Date1 is before Date2!");
   } else if (d1.compareTo(d2) == 0) {
      System.out.println("Date1 is equal to Date2!");
   } else {
      System.out.println("How to get here?");
}

Example

 Live Demo

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
   public static void main(String[] args) throws ParseException {
      SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
      Date d1 = s.parse("2018-10-15");
      Date d2 = s.parse("2018-11-10");
      if (d1.compareTo(d2) > 0) {
         System.out.println("Date1 is after Date2!");
      } else if (d1.compareTo(d2) < 0) {
         System.out.println("Date1 is before Date2!");
      } else if (d1.compareTo(d2) == 0) {
         System.out.println("Date1 is equal to Date2!");
      } else {
         System.out.println("How to get here?");
      }
   }
}

Output

Date1 is before Date2!

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

113 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements