Date

Compare Date objects with after method

In this example we shall show you how to compare Date objects with after(Date when) method of Date, that tests if a Date is after the specified one. To compare a Date object with another Date object, using after(Date when) API method of Date one should perform the following steps:

  • Use the simple Date() constructor, to allocate a Date object and initialize it so that it represents the time at which it is allocated, measured to the nearest millisecond.
  • Use getInstance() API method of Calendar to get a Calendar object, using the default time zone and locale.
  • Use set(int field, int value) API method of Calendar to set a value to the calendar object. The field is set to Calendar.YEAR and the value is set to a past year in the example.
  • Get the Date object that represents this calendar’s time value, with millisecond offset from the January 1 1970 00:00:00.000 GMT, using getTime() API method of Calendar.
  • Use after(Date when) API method of Date. The method returns true if and only if the instant represented by this Date object is strictly later than the instant represented by when, as in the example, and false otherwise.

Let’s take a look at the code snippet that follows.

package com.javacodegeeks.snippets.core;

import java.util.Calendar;
import java.util.Date;

public class CompareDateObjectsWithAfterMethod {
	
	public static void main(String[] args) {
		
		Date now = new Date();
		
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, 1990);
		
		Date past = c.getTime();
		
		if (now.after(past)) {
			System.out.println(now + " is after " + past);
		}
		
	}

}

Output:

Thu Oct 20 16:14:42 EEST 2011 is after Sat Oct 20 16:14:42 EET 1990

 
This was an example of how to compare Date objects with after(Date when) method of Date 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
Inline Feedbacks
View all comments
Back to top button