Home >Web Front-end >JS Tutorial >How Can I Accurately Calculate the Difference in Days Between Two Dates in JavaScript?
Accurately Calculating Date Differences in JavaScript
Determining the difference between two dates is a common task in programming. In JavaScript, the challenge lies in obtaining an accurate full-day difference, excluding any fractional parts.
Previous attempts using date2.getDate() - date1.getDate() may have failed due to inconsistencies in the underlying date handling.
Resolving the Problem
To calculate the full-day difference correctly, we can utilize the following approach:
const date1 = new Date('7/13/2010'); const date2 = new Date('12/15/2010'); const diffTime = Math.abs(date2 - date1); const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
In this code:
By outputting diffTime and diffDays, we obtain the time difference in milliseconds and the full-day difference, respectively.
The above is the detailed content of How Can I Accurately Calculate the Difference in Days Between Two Dates in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!