Tuesday, August 3, 2010

java date compare


if you ever tried to compare java dates, you will get unexpected results if you do not consider time component of java date, for example if you try to compare 2010-08-03 with 2010-08-01,
then you can see that date1 is greater and the difference is 2 day, but if you write java code as below.
import java.util.Calendar;
 
public class TestDateCompare {
 
    private final long MILLSECS_PER_DAY = 24 * 60 * 60 * 1000;
 
    public TestDateCompare() throws InterruptedException{
 
        Calendar today = Calendar.getInstance();        
 
     // Add 2 second delay so we can have difference between 2 dates
 
        Thread.sleep(2000);        
 
        Calendar yesterday = Calendar.getInstance();
 
        //Substract 2 days from today
 
        yesterday.add(Calendar.DATE, -2);
 
        long numOfDaysDifference = ( today.getTime().getTime() - yesterday.getTime().getTime() )/ MILLSECS_PER_DAY;
 
         //This should print output as 2, but it prints output as 1, 
 
        System.out.println("Num of days difference " + numOfDaysDifference);
 
        System.out.println("Yesterday " + yesterday.getTime());
 
        System.out.println("Today " + today.getTime());
 
        }
 
    public static void main(String[] args) throws InterruptedException {
 
        new TestDateCompare();
 
    }
 
}
The out put of this class is
Num of days difference 1
Yesterday Sun Aug 01 11:31:43 EDT 2010
Today Tue Aug 03 11:31:41 EDT 2010
As you can see there is 2 seconds difference, which throws the calculation off, so to make this work add following lines of code before doing date calculation
        today.set(Calendar.HOUR, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        today.set(Calendar.MILLISECOND, 0);
        
        yesterday.set(Calendar.HOUR, 0);
        yesterday.set(Calendar.MINUTE, 0);
        yesterday.set(Calendar.SECOND, 0);
        yesterday.set(Calendar.MILLISECOND, 0);
Do not forget millisecond also, as it may throw off the calculation
After this change the output is as below

Num of days difference 2
Yesterday Sun Aug 01 00:00:00 EDT 2010
Today Tue Aug 03 00:00:00 EDT 2010

There are many other alternatives, like using BigDate or joda-time,
If you have anymore solutions, please feel free to add to this list