Get difference between 2 dates?
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.
Verified Answer (812 Votes) ✓
const date1 = new Date('7/13/2010'); const date2 = new Date('12/15/2010'); const diffTime = Math.abs(date2 - date1); const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); console.log(diffDays);
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.
Answer #2 (725 Votes)
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?
Answer #3 (93 Votes)
Here is a solution using moment.js:
var a = moment('7/11/2010','M/D/YYYY'); var b = moment('12/12/2010','M/D/YYYY'); var diffDays = b.diff(a, 'days'); alert(diffDays);
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