Calendar
Compare Dates with before method
With this example we are going to demonstrate how to compare Dates with before(Object when) method of the Calendar class. In short, to compare a Calendar to another one with before(Object when) method of Calendar you should:
- Use
getInstance()API method of Calendar, in order to get two Calendar objects, using the default time zone and locale. - Use
set(int field, int value)API method of Calendar, in order to set a past value, e.g. year to one of the calendar objects. - Compare the two calendars, using
before(Object when)method of Calendar. The calendar that calls the method is thepastCalendarin the example that is set to represent a past date, so it represents a time before the time represented by the other calendar and the method returns true.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
import java.util.Calendar;
public class CompareDatesWithBeforeMethod {
public static void main(String[] args) {
Calendar currentCalendar = Calendar.getInstance();
Calendar pastCalendar = Calendar.getInstance();
// set calendar to past date
pastCalendar.set(Calendar.YEAR, 1999);
if (pastCalendar.before(currentCalendar)) {
System.out.println(pastCalendar.getTime() + " is before " + currentCalendar.getTime());
}
}
}
Output:
Tue Oct 19 23:01:06 EEST 1999 is before Wed Oct 19 23:01:06 EEST 2011
This was an example of how to compare Dates with before(Object when) method of Calendar in Java.
