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


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

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

Calendar date1 = Calendar.getInstance();
date1.set(Calendar.YEAR, 2010);
date1.set(Calendar.MONTH, 11);
date1.set(Calendar.DATE, 20);

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

The following is an 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, 2010);
      date1.set(Calendar.MONTH, 11);
      date1.set(Calendar.DATE, 20);
      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.before(date2)) {
         System.out.println("Date One is before Date Two!");
      } else {
         System.out.println("Date One is after Date Two!");
      }
   }
}

Output

Date One = Mon Dec 20 06:48:11 UTC 2010
Date Two = 11-23-2018
Date One is before Date Two!

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 29-Jun-2020

132 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements