Hi guys,
I have a need to calculate number of days between two dates. After looking up google I wrote this static method:
public static int getDaysDifference(Date startDate, Date endDate)
{
System.out.println("startDate=" + startDate);
System.out.println("endDate=" + endDate);
long diff = endDate.getTime() - startDate.getTime();
System.out.println("diff=" + diff);
int days = (int) (diff/(1000*60*60*24));
System.out.println("days=" + days);
return days;
}
The above code works ok but when startDate is Apr 1, 2007 and endDate is Apr 2, 2007 it is returning me 0 days which is wrong. I found out :
startDate endDate diff days
-------------------------------------------------------------------------------------
Sat Mar 31 00:00:00 EST 2007 Sun Apr 01 00:00:00 EST 2007 86400000 1
Sun Apr 01 00:00:00 EST 2007 Mon Apr 02 00:00:00 EDT 2007 82800000 0
Mon Apr 02 00:00:00 EDT 2007 Tue Apr 03 00:00:00 EDT 2007 86400000 1
I dont understand why diff is 82800000 and not 86400000 when startDate is Apr 1, 2007 and endDate is Apr 2, 2007. Can somebody please explain?
What is the way to fix this problem? I need a solution which works in all scenarios.
Thanks