Ive been searching quite a lot find an answer for this , and couldn’t find one.
I have 2 dates ,
I want to calc days between them
but I Also want the end day to be counted.
Example :
- me and my wife go to hotel from [20 jan] till [26 Jan] , so its 7 days total.
the only code which I find working is :
Math.round((b - a) / ( 1000 * 60 * 60 * 24)) +1
where :
var a= new Date (y,0,20);
var b= new Date (y,0,26);
I also made a nested loop to test all months within a 150 years , and it works Ok.
var y = 1970;
var m = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
for(var i = 0; i < 150; i++)
{
for(var j = 0; j < 12; j++)
{
var a = new Date(y + i, m[j], 20);
var b = new Date(y + i, m[j], 26);
var days = Math.round((b - a) / (1000 * 60 * 60 * 24)) + 1;
if(days != 7) console.log(i + y); //tell me if result is unexpected.
}
}
console.log('-FINISH-' + new Date().getTime())
So where is the problem ?
I can’t figure how the math function like round can do the trick here.
We are talking about milliseconds here and I can’t see where the round behavior gives me the right result.
(p.s. – forget about ceil and floor , they do not help here and have inconsistent results) , I have also tried to add one day to the b value , and use ceil || floor but with no success
The reason your rounding is working is because you’re only working with full days.
myDate.getTime()will yield the number of milliseconds since 1970-01-01. If you’re always assigning your dates asnew Date(y,m,d)you will always have thetimepart set to00:00:00.000, and hence the date comparison will always yield a multiple of 86400000, which is your divisor. The rounding here is for the most part superfluous.If you’re creating all of your dates as specified above, the only time rounding does come into play, is when the daylight savings offset at date
bis different from that at datea.roundwill take care of these discrepancies, as they’re rarely more than an hour.From your script, October 1970 is problematic (in CEST) because Oct 20th is in daylight savings, and Oct 26th isn’t.
You could work around this by rounding, or by using UTC dates