Dates Comparison Java

It is many times required in coding to compare two dates like one is before the other or after or equals (like dates of joining a job). To manipulate dates, Java comes with mainly two classes from java.util package Date and Calendar (its subclass GregorianCalendar).

Three programs are given to compare dates with classes Date, Calendar in combination with SimpleDateFormat.

Following program on Dates Comparison Java uses java.util.Calendar class.
import java.util.*;

public class DateCompare1
{
  public static void main(String args[])
  {				// GET CURRENT DATE
    Calendar cal1 = Calendar.getInstance();  
                               // WRITE A DATE BEFORE CURRENT DATE
    Calendar cal2 = Calendar.getInstance();  
    cal2.set(2011, Calendar.MARCH, 12);

    if(cal1.before(cal2))
      System.out.println("Yes, before");
    else if(cal1.after(cal2))
      System.out.println("Yes, after");
    else if(cal1.equals(cal2))
      System.out.println("Yes, equals");

    cal2.set(2011, Calendar.SEPTEMBER, 20);
    if(cal2.after(cal1))
      System.out.println("Yes, cal2 is after cal1");
  }
}


Dates Comparison Java
Output screenshot on Dates Comparison Java

Calendar cal1 = Calendar.getInstance();

Calendar is an abstract class and being an abstract class its object can be obtained with its static getInstance() method. That is, the getInstance() method returns an object of Calendar, cal1, containing all the current time particulars like year, month and date etc.

Calendar cal2 = Calendar.getInstance();
cal2.set(2011, Calendar.MARCH, 12);

Another object cal2 is obtained for which our choicest date is set. MARCH (instance variable) is a field of Calendar class.

before(), after() and equals() are the methods of Calendar class with which two dates can be compared whether one before, after or equals.

General explanation is available on class Calendar.

Following program on Dates Comparison Javauses SimpleDateFormat in combination with Date.
import java.text.*;  // for ParseException and SimpleDateFormat
import java.util.*;  // for Date

public class DateCompare2 
{
  public static void main(String[] args)
  {
    try
    { 
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

      Date thisDay = sdf.parse("2011-09-05");   // get today

      Date someDay = sdf.parse("2012-12-30");  // set some date either before, after or same

      System.out.println("thisDay: " + thisDay);
      System.out.println("someDay: " + someDay);

      if(thisDay.before(someDay))
        System.out.println("\nthisDay is before someDay");
      else if(thisDay.after(someDay))
        System.out.println("thisDay is after someDay");
      else if(thisDay.equals(someDay))
        System.out.println("thisDay and someDay are same");
    }
    catch(ParseException e)
    {
      System.out.println("Unable to parse to Date. " + e);
    }
  }
}


Dates Comparison Java
Output screenshot on Dates Comparison Java

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd”);

SimpleDateFormat from java.text package allows the programmer to choose the format of date. In the above statement, the year is chosen in four digits, month in two digits and date in two digits.

Date thisDay = sdf.parse(“2011-09-05”);

The parse() method of SimpleDateFormat converts the specified date in string format into an object of Date class. This method throws a checked exception ParseException when unable to parse and is handled in catch block.

The Date class methods before(), after() and equals() are used to compare the dates thisDay and someDay.

Separate explanation is available on class Calendar, TimeZone and Locale and class GregorianCalendar.

In the following program on Dates Comparison Java compareTo() method of Date class is used to compare.
import java.util.Date;
public class DateCompare3
{
  public static void main(String args[])
  {
    Date firstDate = new Date();

    try
    {
      Thread.sleep(1000);
    }
    catch(InterruptedException e)
    {
      e.printStackTrace();
    }

    Date secondDate = new Date();

    int x = firstDate.compareTo(secondDate);
    System.out.println(x);              // prints -1
  }
}

Date firstDate = new Date();

Two Date objects firstDate and secondDate are created with an interval of 1000 milliseconds. The Date object embeds the current system time. The secondDate is after the firstDate.

int x = firstDate.compareTo(secondDate);
System.out.println(x);

The comapareTo() method returns an integer value depending on the status of comparison. The method returns 0 if the date passed as parameter is the same as calling object; returns less than 0 when the calling object is earlier to the one passed as parameter and more than 1 when calling object is later. In the code, as firstDate is earlier than secondDate, it returned -1.

Leave a Comment

Your email address will not be published.