Basile Copin - 2 months ago 15
Javascript Question

# JS - Calculate number of days between 2 dates considering leap year

I want to calculate the number of days between 2 dates. Common problem.

For exemple :

``````var d0 = new Date("2016-02-27");
var d1 = new Date("2017-08-25");
``````

Many people recommend using epoch difference :

``````var res = (d1 - d0) / 1000 / 60 / 60 / 24;
// res = 545 days
``````

But I was doubtful so I wrote a naive function :

``````function days(d0, d1)
{
var d = new Date(d0);
var n = 0;
while(d < d1)
{
d.setDate(d.getDate() + 1);
n++;
}
return n;
}
``````

This function and epoch difference essentially output the same result but not with my particuliar exemple. Probably because 2016 is a leap year.

``````res = days(d0, d1);
// res = 546 days
``````

Any idea why ?

After testing, it appears that the loop stop at `2017-08-26`, instead of `2017-08-25`.

When you print the value of `d0` and `d1`, here is the result :

d0: Sat Feb 27 2016 01:00:00 GMT+0100 (Central Europe Standard Time)

d1: Fri Aug 25 2017 02:00:00 GMT+0200 (Central Europe Daylight Time)

As you can see, there is a one-hour shift between the two dates, so when the index of the loop reaches Aug 25 2017, this shift is still there and makes the "lower than" operation true, where it should be false.

Make sure to normalize your dates before using it.