Date

Compare Date objects with compareTo method

With this example we are going to demonstrate how to compare Date objects with compareTo method of the Date class. In short, to compare a Date object with another 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, 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. The method returns a Date object representing this Calendar’s time value, with millisecond offset from the January 1 1970 00:00:00.000 GMT.
  • Invoke compareTo(Date anotherDate) API method of Date, using the two Date objects. The method compares the two Dates for ordering and returns an int value, that is 0 if the argument Date is equal to the Date tat calls the method, a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.

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 CompareDateObjectsWithCompareToMethod {
	
	public static void main(String[] args) {
		
		Date now = new Date();
		
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, 2100);
		
		Date future = c.getTime();
		
		int d = now.compareTo(future);
		
		if (d<0) {
			System.out.println(now + " is before " + future);
		}
		else if (d>0) {
			System.out.println(now + " is after " + future);
		}
		else {
			System.out.println("Dates are equal");
		}
		
	}

}

Output:

Thu Oct 20 16:19:55 EEST 2011 is before Wed Oct 20 16:19:55 EEST 2100

 
This was an example of how to compare Date objects with compareTo(Date anotherDate) 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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button