Date Arithmetic: Adding Months and Years
You'll learn how to safely add or subtract months and years to JavaScript dates while avoiding common pitfalls with month-end edge cases.
The Core Challenge
While adding days is straightforward (just increment the timestamp), adding months and years is trickier because months have different lengths. When you add a month to January 31st, should you get February 31st (which doesn't exist) or something else? JavaScript's setMonth() and setFullYear() handle this automatically, but you need to understand their behavior.
Adding Months with setMonth()
Use setMonth() with the current month plus your offset:
const date = new Date('2024-01-15');
date.setMonth(date.getMonth() + 3); // Add 3 months
console.log(date); // 2024-04-15
The Month-End Edge Case
When the target month has fewer days, JavaScript overflows into the next month:
const jan31 = new Date('2024-01-31');
jan31.setMonth(jan31.getMonth() + 1); // Add 1 month
console.log(jan31); // 2024-03-02 (NOT February 29!)
January 31 + 1 month = February 31... but February only has 29 days in 2024, so it becomes March 2nd.
Adding Years with setFullYear()
Adding years works similarly:
const date = new Date('2020-02-29'); // Leap year
date.setFullYear(date.getFullYear() + 1);
console.log(date); // 2021-03-01 (overflow because Feb 29 doesn't exist in 2021)
Handling Negative Values
Both methods accept negative values for subtraction:
const date = new Date('2024-05-15');
date.setMonth(date.getMonth() - 2); // Subtract 2 months
console.log(date); // 2024-03-15
Key Takeaway: Use setMonth() and setFullYear() for adding/subtracting time periods, but always test month-end dates carefully—JavaScript will overflow to the next month when the day doesn't exist in the target month.