How to find the difference between two dates
Short answer
Subtracting dates gives the difference in milliseconds. Divide it by the number of milliseconds in a day:
const start = new Date(2025, 0, 1);
const end = new Date(2025, 2, 15);
const msPerDay = 24 * 60 * 60 * 1000;
console.log(Math.round((end - start) / msPerDay));Output:
73Adding days to a date
setDate() rolls over into the next month when the day count exceeds the current month:
const date = new Date(2025, 0, 30);
date.setDate(date.getDate() + 5);
console.log(date.toLocaleDateString('ru-RU'));Output:
04.02.2025Hours and minutes
Divide the difference by the number of milliseconds in an hour or a minute:
const start = new Date(2025, 0, 1, 9, 15);
const end = new Date(2025, 0, 1, 17, 45);
const minutes = (end - start) / 60000;
console.log(Math.floor(minutes / 60) + ' h ' + (minutes % 60) + ' min');Output:
8 h 30 minCommon mistake
Because of the switch to daylight saving time a day may last 23 or 25 hours. Round the number of days with Math.round(), otherwise you may get 72.96 instead of 73. Comparing dates in UTC avoids the problem completely:
const start = Date.UTC(2025, 2, 1);
const end = Date.UTC(2025, 3, 1);
console.log((end - start) / 86400000);Output:
31Functions used in this recipe
- Date.prototype.getTime — Returns the date as a number of milliseconds.
- Math.round — Rounds a number to the nearest integer.