Home » Core Java » util » Calendar » Compare Dates with before method

About Byron Kiourtzoglou

Avatar photo
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.

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments