Java Program to compare dates if a date is after another date

Java 8Object Oriented ProgrammingProgramming

To compare dates if a date is after another date, use the Calendar.after() method.

The Calendar.after() method returns whether this Calendar's time is after the time represented by the specified Object. First, let us set a date which is after (future date) the current date

Calendar date1 = Calendar.getInstance();
date1.set(Calendar.YEAR, 2040);
date1.set(Calendar.MONTH, 10);
date1.set(Calendar.DATE, 25);

Here is our current date

Calendar date = Calendar.getInstance();

Now, use the after() method to compare both the dates as shown in the following example

Example

 Live Demo

import java.util.Calendar;
public class Demo {
   public static void main(String[] args) {
      Calendar date1 = Calendar.getInstance();
      date1.set(Calendar.YEAR, 2040);
      date1.set(Calendar.MONTH, 10);
      date1.set(Calendar.DATE, 25);
      java.util.Date dt = date1.getTime();
      System.out.println("Date One = "+dt);
      Calendar date2 = Calendar.getInstance();
      System.out.println("Date Two = " + (date2.get(Calendar.MONTH) + 1) + "-" +
      date2.get(Calendar.DATE) + "-" + date2.get(Calendar.YEAR));
      if(date1.after(date2)) {
         System.out.println("Date One is after Date Two!");
      } else {
         System.out.println("Date One is before Date Two!");
      }
   }
}

Output

Date One = Sun Nov 25 06:52:14 UTC 2040
Date Two = 11-23-2018
Date One is after Date Two!
raja
Published on 19-Dec-2018 17:45:37
Advertisements