Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Days Difference betwen 2 dates

807605Aug 20 2007 — edited Oct 11 2007
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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 8 2007
Added on Aug 20 2007
11 comments
290 views