How to Find Number of Days Between Dates in JavaScript
To find the number of days between two dates in JavaScript, subtract the earlier date from the later date to get the difference in milliseconds using
Date objects, then divide by 1000 * 60 * 60 * 24 to convert milliseconds to days. Use Math.abs() to ensure the result is positive regardless of date order.Syntax
Use the following pattern to calculate days between two dates:
date1anddate2are JavaScriptDateobjects.- Subtracting them gives the difference in milliseconds.
- Divide by
1000 * 60 * 60 * 24to convert milliseconds to days. Math.abs()ensures the result is positive.
javascript
const diffTime = Math.abs(date2 - date1); const diffDays = diffTime / (1000 * 60 * 60 * 24);
Example
This example shows how to calculate the number of days between two specific dates and print the result.
javascript
const date1 = new Date('2024-06-01'); const date2 = new Date('2024-06-15'); const diffTime = Math.abs(date2 - date1); const diffDays = diffTime / (1000 * 60 * 60 * 24); console.log(`Number of days between dates: ${diffDays}`);
Output
Number of days between dates: 14
Common Pitfalls
Common mistakes include:
- Not using
Math.abs(), which can give negative results if dates are reversed. - Forgetting to convert milliseconds to days by dividing by
1000 * 60 * 60 * 24. - Using date strings without proper format, which can cause inconsistent parsing.
javascript
/* Wrong way: might give negative result */ const diffTimeWrong = date1 - date2; const diffDaysWrong = diffTimeWrong / (1000 * 60 * 60 * 24); /* Right way: use Math.abs() */ const diffTimeRight = Math.abs(date2 - date1); const diffDaysRight = diffTimeRight / (1000 * 60 * 60 * 24);
Quick Reference
Remember these key points when calculating days between dates:
- Use
Dateobjects for accurate date handling. - Subtract dates to get milliseconds difference.
- Divide by
86400000(milliseconds in a day) to convert to days. - Use
Math.abs()to avoid negative results.
Key Takeaways
Subtract two Date objects to get the difference in milliseconds.
Divide the difference by 86400000 to convert milliseconds to days.
Use Math.abs() to ensure the day count is always positive.
Always create Date objects with valid date strings or timestamps.
Beware of time zones and daylight saving changes when calculating days.