Date

Compare Date objects with before method

This is an example of how to compare Date objects with before(Date when) API method of Date. Comparing a Date with another Date using before(Date when) method implies that you should:

  • Create a new Date object, using the Date() constructor, that allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
  • Create a new Calendar object, using getInstance() API method of Calendar, that gets a calendar using the default time zone and locale.
  • Use set(int field, int value) API method of Calendar to set a future value, e.g. year to the calendar object.
  • Use getTime() API method of Calendar, in order to get a Date object that represents this calendar’s time value, with millisecond offset from the January 1 1970 00:00:00.000 GMT.
  • Use before(Date when) API method of Date to compare the two Date objects. The method tests if the Date object calling it is before the specified date. It returns true if and only if the instant of time represented by this Date object is strictly earlier than the instant represented by when 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 CompareDateObjectsWithBeforeMethod {
	
	public static void main(String[] args) {
		
		Date now = new Date();
		
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, 2100);
		
		Date future = c.getTime();
		
		if (now.before(future)) {
			System.out.println(now + " is before " + future);
		}
		
	}

}

Output:

Thu Oct 20 16:16:40 EEST 2011 is before Wed Oct 20 16:16:40 EEST 2100

 
This was an example of how to compare Date objects with before(Date when) API method of Date 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