Compare date time using before() method of Java Calendar

Java 8Object Oriented ProgrammingProgramming

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 in the past (past date)

Calendar beforeDate = Calendar.getInstance();
beforeDate.set(Calendar.YEAR, 2010);
beforeDate.set(Calendar.MONTH, 05);
beforeDate.set(Calendar.DATE, 30);

Here is our date, which is 11-22-2018

Calendar currentDate = Calendar.getInstance();

Now, use the before() 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 beforeDate = Calendar.getInstance();
      beforeDate.set(Calendar.YEAR, 2010);
      beforeDate.set(Calendar.MONTH, 05);
      beforeDate.set(Calendar.DATE, 30);
      java.util.Date dt = beforeDate.getTime();
      System.out.println("Past Date = "+dt);
      Calendar currentDate = Calendar.getInstance();
      System.out.println("Current date = " + (currentDate.get(Calendar.MONTH) + 1) + "-" +
      currentDate.get(Calendar.DATE) + "-" + currentDate.get(Calendar.YEAR));
      System.out.println("Date "+dt+ " is before current date? = " +          beforeDate.before(currentDate));
      }
}

Output

Past Date = Wed Jun 30 13:14:28 UTC 2010
Current date = 11-22-2018
Date Wed Jun 30 13:14:28 UTC 2010 is before current date? = true
raja
Published on 19-Dec-2018 14:52:11
Advertisements