javascript wrong date / days calculation

126 views Asked by At

I need to calculate the number of nights between 2 dates, it works but it's very odd.

If I pick dates like 22,06,2015 and 22,07,2015 it shows me 31 nights, which is wrong since June has only 30 days.

if I pick dates like 01,07,2015 and 31,07,2015 it shows me 30 nights, which is correct.

if I pick dates like 01,07,2015 and 1,08,2015 it shows me 31 nights etc.

if I pick dates like 30,09,2015 and 30,10,2015 it shows me 31.041666666666668 nights which is odd and incorrect.

Hope you can help me with this one. Here's the code:

var date11 = $("#in").val();
var date22 = $("#out").val();

// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date111 = date11.split('-');
date222 = date22.split('-');

// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date111[2], date111[1], date111[0]);
date2 = new Date(date222[2], date222[1], date222[0]);

// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);

// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;

// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;

// and finaly, in days :)
var timeDifferenceInDays = timeDifferenceInHours  / 24;

Thanks a million!

1

There are 1 answers

0
RobG On BEST ANSWER

You aren't subtracting 1 from the calendar month number:

date1 = new Date(date111[2], date111[1] - 1, date111[0]);
                                --------^^^^

Months are zero indexed. you should probably also round the result as if you cross a daylight saving boundary, the time value won't be an even number of days, it will be out by 1 hour (unless you cross two boundaries…)