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 the pastCalendar in 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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button