1
votes

i use two datepickers to get the arrival and the departure date, counting the days for the number of nights, all is working nice, except one thing: if i take my startdate on 29.10.2011 and my enddate on the 31.10.2011 jquery counts 3 nights but there only 2 nights. Only in october, other month still working fine, hope someone could help me to figure out where my mistake is:

var oneDay = 1000*60*60*24; 
var difference = Math.ceil((arrivalDate.getTime() - departureDate.getTime()) / oneDay); 
4

4 Answers

3
votes

The problem is that daylight saving time ends on 30th October in Europe (where, going by the German error message, you are). As a result, where there would normally be 24+24+24=72 hours between the dates, in this case, there are 24+24+24+1=73 hours between the dates. Your code therefore works out that there are 2.041666 days between the dates. Your Math.ceil then rounds this up to 3.

The simplest solution to this in this case is probably just to replace Math.ceil with Math.round. When DST ends, your 2.04166 days will be rounded to 2 days. When DST starts, the 1.95834 days you'll work out then will also be rounded to 2 days.

0
votes

change:

var difference = Math.ceil((arrivalDate.getTime() - departureDate.getTime()) / oneDay); 

to:

var different = Math.Floor(arrivalDate.getTime() / oneDay) - Math.Floor(departureDate.getTime() / oneDay)
0
votes

March should not get messed up, because it just one hour less, so it still gets round up to 24 hours, if i'm correct?

Greetings Ralf

0
votes

The following correctly reports 2 'nights' or in fact 2 days.

var startDate = new Date(2011,10,29);
var endDate = new Date(2011,10,31);
var oneDay = 1000*86400;
var difference = Math.ceil((endDate.getTime() - startDate.getTime())/oneDay);
alert(difference);

I suspect the problem is with the time aspect of the Date object. You could 'clean' the inputs by removing the time element thus.

function JustDate(inputDate) {
    return new Date(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate());
}

var departureDate = JustDate(departure.datepicker("getDate"));
var arrivalDate = JustDate(arrival.datepicker("getDate"));