0

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!

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Mikey
  • 3
  • 2
  • 1
    That's the first time I've ever seen dates separated by commas instead of, say, periods, or slashes, or hyphens. Maybe you could reformat using ISO yyyy-mm-dd standard? – Nathan Tuggy Jun 23 '15 at 02:08
  • Hopefully this will help you!!!! http://stackoverflow.com/questions/26453996/calculate-days-left-to-a-specific-date-with-javascript?rq=1 – jshuadvd Jun 23 '15 at 02:09
  • http://stackoverflow.com/a/2483476/4535386 – YesItsMe Jun 23 '15 at 02:10

1 Answers1

0

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…)

RobG
  • 142,382
  • 31
  • 172
  • 209