JSF Marquee Component | Java Example | FlexiGrid using Servlet + JSON |

Date Comparison without time

leave a comment »

I wanted to compared 2 java.util.Date objects. I created 2 date objects with a delay of 1 sec each , when i compare d1 with d2 using compareTo, it returns -1 , i was expecting 0 assuming both objects to be created on same day.

This is the my test program to compare dates.

import java.util.Date;
public class DateCompare {
public static void main(String[] args) {
Date d1 = new Date();
try {
} catch (InterruptedException e) {     }
Date d2 = new Date();
System.out.println(” compare ” + d1.compareTo(d2));

i.e d1 is lesser than d2. When we use compareTo function of Date, it compares the date, time, hours, min etc etc and returns -1

we can setHours, minutes, seconds to 0 in date object before comparison but is deprecated. This is the util method i used to date comparison avoiding time

public static int compareDate(Date d1, Date d2) throws NullPointerException {

if (d1 == null || d2 == null) {
throw new NullPointerException(” date cannot be null”);

Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR, 0);
cal1.set(Calendar.AM_PM, 0);
cal1.set(Calendar.HOUR_OF_DAY, 0);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
cal1.set(Calendar.MILLISECOND, 0);

Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.HOUR, 0);
cal2.set(Calendar.AM_PM, 0);
cal2.set(Calendar.HOUR_OF_DAY, 0);
cal2.set(Calendar.MINUTE, 0);
cal2.set(Calendar.SECOND, 0);
cal2.set(Calendar.MILLISECOND, 0);

return cal1.compareTo(cal2);


if the above method doesn’t work as expected, print cal1 and cal2 before calling compareTo and check which attributes are different, if you find anything different set it to ‘0’ using .set method. just like i have set HOUR, AM_PM ect to 0.


Written by speedrace703

December 16, 2009 at 7:05 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: