Reputation: 20173
This is how I had it done:
var sDate = $('.start input').datepicker('getDate').getTime();
var nDate = $('.end input').datepicker('getDate').getTime();
var dias = Math.floor((nDate - sDate)/1000/60/60/24) + 1;
But it fails
20/03/2014 to 30/03/2014
-> 11
days
and
21/03/2014 to 31/03/2014
-> 10
days, when the difference is the same,
Where is the flaw?
Upvotes: 1
Views: 1157
Reputation: 3362
The right code is this (as @vinod-gubbala stated above):
var dias = Math.round((nDate - sDate)/(1000*60*60*24));
Basically, you get the difference in (milliseconds) of the days and divide them by 1000 (to concert to seconds) * 60 (60 seconds per minute) * 60 (60 minutes per hour) * 24 (24 hours a day).
Don't know why you are adding +1
at the end. Of course this will work with complete days, I mean, comparing dates with he same time.
The problem you are experiencing could be something with the daylight saving time. Have in mind that for 2014, the last sunday of march (march 30th) there is a time change (at least in Europe), so there is an hour less and your function, as it do a floor, rounds down and you lose a day.
Regards.
Upvotes: 1
Reputation: 6120
I did this:
var d1 = new Date('2013-03-20 00:00:00')
var d2 = new Date('2013-03-30 00:00:00')
(d2.getTime() - d1.getTime()) / 1000 / 60 / 60 / 24 + 1; //11
And then this:
var d1 = new Date('2013-03-21 00:00:00')
var d2 = new Date('2013-03-31 00:00:00')
(d2.getTime() - d1.getTime()) / 1000 / 60 / 60 / 24 + 1; //11
So there is no flaw there, most likely it's an error in creation of Date() object of the jQuery datepicker. I suggest you do the following:
console.log(nDate,sDate);
console.log(((nDate - sDate)/1000/60/60/24)+1);
And see what does that give you for both dates. You might spot an error there.
Upvotes: 0
Reputation: 1463
Take a look at http://momentjs.com/
Your code will look like:
var a = moment($('.start input').datepicker('getDate').getTime());
var b = moment($('.end input').datepicker('getDate').getTime());
d = a.diff(b, 'days')
Upvotes: 0
Reputation: 754
You have to round instead of floor.
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var sDate = $('.start input').datepicker('getDate').getTime();
var nDate = $('.end input').datepicker('getDate').getTime();
var diffDays = Math.round(Math.abs((nDate - sDate)/(oneDay)));
Upvotes: 1