Date Arithmetic
Calculate date differences and add/subtract time by working with millisecond timestamps.
Calculate date differences and add/subtract time by working with millisecond timestamps.
const ONE_DAY = 24 * 60 * 60 * 1000;
// Days between two dates
const start = new Date("2024-01-01");
const end = new Date("2024-12-31");
const days = Math.round((end - start) / ONE_DAY); // 365
// Add days to a date
function addDays(date, n) {
return new Date(date.getTime() + n * ONE_DAY);
}
addDays(new Date("2024-06-01"), 30); // July 1, 2024
// Subtract months
const d = new Date("2024-06-15");
d.setMonth(d.getMonth() - 1); // May 15, 2024
Avoid adding days with setDate() across month boundaries — it overflows correctly but is harder to read than timestamp arithmetic.
More in JavaScript