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

About Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Compare Dates with after method

This is an example of how to compare Dates with after(Object when) method of the Calendar class. Comparing a Calendar object to another using after(Object when) method of Calendar implies that 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 future value, e.g. year to one of the calendar objects.
  • Compare the two calendars, using after(Object when) method of Calendar. The calendar object that invokes the method is the futureCalendar in the example and it is set to represent a future date, so it represents a time after 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 CompareDatesWithAfterMethod {
	
	public static void main(String[] args) {
		 
		Calendar currentCalendar = Calendar.getInstance();
		
		Calendar futureCalendar = Calendar.getInstance();
		 
		// set calendar to future date
		futureCalendar.set(Calendar.YEAR, 2066);
		 
		if (futureCalendar.after(currentCalendar)) {
			System.out.println(futureCalendar.getTime() + " is after " + currentCalendar.getTime());
		}
		
	}

}

Output:

Tue Oct 19 22:54:53 EEST 2066 is after Wed Oct 19 22:54:53 EEST 2011

 
This was an example of how to compare Dates with after(Object when) method of the Calendar class 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

 

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