Calculating the Difference Between Two Dates in JavaScript
This inquiry seeks to determine the full-day difference between two dates in JavaScript. While the presented solution using getDate() may not yield the desired outcome, here's a reliable alternative:
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));
This approach calculates the time difference in milliseconds using the Math.abs() function to ensure a positive result. Next, it converts the time difference to days by dividing it by the number of milliseconds in a day. Finally, the Math.floor() function rounds the result down to the nearest whole day.
The provided code snippet demonstrates the usage of this solution, displaying both the time difference in milliseconds and the full-day difference between two arbitrary dates.
The above is the detailed content of How Can I Calculate the Difference in Days Between Two Dates in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!