Java Program to Match Dates

Java 8Object Oriented ProgrammingProgramming

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!
raja
Published on 06-Dec-2018 07:11:23
Advertisements