This question already has an answer here:
How do I get the difference between 2 dates in full days (I don't want any fractions of a day)
var date1 = new Date('7/11/2010');
var date2 = new Date('12/12/2010');
var diffDays = date2.getDate() - date1.getDate();
alert(diffDays)
I tried the above but this did not work.
A more correct solution
... since dates naturally have time-zone information, which can span regions with different day light savings adjustments
Previous answers to this question don't account for cases where the two dates in question span a daylight saving time (DST) change. The date on which the DST change happens will have a duration in milliseconds which is
!= 1000*60*60*24
, so the typical calculation will fail.You can work around this by first normalizing the two dates to UTC, and then calculating the difference between those two UTC dates.
Now, the solution can be written as,
This works because UTC time never observes DST. See Does UTC observe daylight saving time?
p.s. After discussing some of the comments on this answer, once you've understood the issues with javascript dates that span a DST boundary, there is likely more than just one way to solve it. What I provided above is a simple (and tested) solution. I'd be interested to know if there is a simple arithmetic/math based solution instead of having to instantiate the two new Date objects. That could potentially be faster.
1000000% sure...............
Here is a solution using moment.js:
I used your original input values, but you didn't specify the format so I assumed the first value was July 11th. If it was intended to be November 7th, then adjust the format to
D/M/YYYY
instead.Here is one way:
Observe that we need to enclose the date in quotes. The rest of the code gets the time difference in milliseconds and then divides to get the number of days. Date expects mm/dd/yyyy format.
I tried lots of ways, and found that using datepicker was the best, but the date format causes problems with JavaScript....
So here's my answer and can be run out of the box.
a Fiddle can be seen here DEMO