Originally Posted by

**Lexilou**
Hi all,

I am new to the boards and new to Javascript and I am looking for some help for on a Date Difference Calculator. I have already created the basics of the page where you can enter the month, day and year but I am not sure who to do the actual script to have it calculate the difference between the two dates. I have named my function dateDiff and want the return to be in a alert box.

Can anyone help out?

Please be advised that no matter how often you see it done - it is a fatal error to use time functions to calculate dates. There will be circumstances when daylight saving transitions introduce an error.

There are complicated ways of doing it efficiently, however here is a simple albeit slow algorithm for simply counting the days. There is no error checking:

Code:

function DateDiff(d1,d2)
{
var dt1=new Date(d1), dt2=new Date(d2), i=0,
date2={day:dt2.getDate(), month:dt2.getMonth(), year:dt2.getFullYear() };
while( dt1.getFullYear() != date2.year)
{
dt1.setDate(dt1.getDate()+1);
i++
}
while( dt1.getMonth() != date2.month)
{
dt1.setDate(dt1.getDate()+1);
i++
}
while( dt1.getDate() != date2.day)
{
dt1.setDate(dt1.getDate()+1);
i++
}
alert(i+' day'+(i!=1?"s":"") );
}
DateDiff("oct 10 2006", "dec 15 2007");