2

I have this function on my calculator that is meant to determine the number of dates between two days:

    function DaysBetween(str1, str2) {
    var date1 = str1;
    var date2 = str2;

    diffDays = (new Date(date2).getTime() - new Date(date1).getTime())/(1000 * 60 * 60 * 24);

    if (diffDays == 0) {
        diffDays = 1;
    }

    return diffDays;
}

but when I put in the values of '10/10/2019', '11/13/2019' it gives me a strange output of 34.041666666666664

here is a fiddle:

function DaysBetween(str1, str2) {
    var date1 = '10/10/2019';
    var date2 = '11/13/2019';

    diffDays = (new Date(date2).getTime() - new Date(date1).getTime())/(1000 * 60 * 60 * 24);
    
    if (diffDays == 0) {
     diffDays = 1;
    }

    console.log (diffDays);
}
<button onclick="DaysBetween()">
Test!
</button>

Can someone help me fix this? Thanks.

  • Because Daylight Saving Time ends on November 3, so there's an extra hour on that day. – Barmar Oct 08 '19 at 16:03
  • You would likely do better to parse the strings to their year, month and day components then simply do `(Date.UTC(y0, m0-1, d0) - Date.UTC(y1, m1-1, d1))/8.64e7`. UTC days are always 24 hours long so aren't affected by daylight saving. – RobG Oct 09 '19 at 12:48

1 Answers1

-1

You need to use Math.round()

function DaysBetween(date1, date2) {
    diffDays = (new Date(date2).getTime() - new Date(date1).getTime())/(1000 * 60 * 60 * 24);
    console.log (Math.round(diffDays));
}

DaysBetween('10/10/2019', '11/13/2019')

34

Mathieu Gemard
  • 514
  • 7
  • 11