Date Arithmetic: Adding and Subtracting Days
You'll learn how to add or subtract days from a date and let JavaScript automatically handle month and year boundaries.
The Core Idea
JavaScript's Date object is surprisingly smart about date arithmetic. When you add or subtract days using setDate() or by manipulating the day value, the Date object automatically rolls over months and years for you. You don't need to worry about "what comes after January 31st?" or "is this a leap year?" — JavaScript handles all that internally.
How It Works
To add days to a date, get the current day with getDate(), add your desired number of days, then set it back with setDate(). JavaScript will automatically adjust the month and year if needed:
const today = new Date(2024, 0, 28); // January 28, 2024
today.setDate(today.getDate() + 5); // Add 5 days
console.log(today); // February 2, 2024 (rolled into next month!)
Subtracting works the same way:
const date = new Date(2024, 2, 3); // March 3, 2024
date.setDate(date.getDate() - 5); // Subtract 5 days
console.log(date); // February 27, 2024 (rolled back to previous month!)
Edge Cases Handled Automatically
JavaScript gracefully handles leap years, month lengths, and year boundaries:
const feb28 = new Date(2024, 1, 28); // Feb 28, 2024 (leap year)
feb28.setDate(feb28.getDate() + 1);
console.log(feb28); // February 29, 2024
const dec30 = new Date(2023, 11, 30); // December 30, 2023
dec30.setDate(dec30.getDate() + 5);
console.log(dec30); // January 4, 2024 (new year!)
Key Takeaway: Use setDate(getDate() + n) to add days or setDate(getDate() - n) to subtract days — the Date object automatically handles all month, year, and leap year rollovers for you.