Calendar

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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He 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