Dates Comparison Java

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.

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.

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.

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);

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 Reply

Your email address will not be published. Required fields are marked *