Date Arithmetic Pitfalls: DST and Month Boundaries
You'll learn to recognize how daylight saving time and varying month lengths create unexpected edge cases when performing date arithmetic.
The Core Challenge
When you add or subtract time from dates, you might expect simple, predictable results. But dates aren't as straightforward as numbers—they exist in a world of irregular month lengths (28, 29, 30, or 31 days) and daylight saving time transitions (where hours can repeat or disappear).
Daylight Saving Time Traps
When a DST transition occurs, a day might have 23 or 25 hours instead of 24. If you're adding "24 hours" versus "1 day," you might end up at different times:
// Spring forward example (DST starts)
const date = new Date(2024, 2, 10, 2, 0); // March 10, 2024, 2:00 AM
const tomorrow = new Date(date);
tomorrow.setDate(date.getDate() + 1); // Adds 1 calendar day
console.log(tomorrow.getHours()); // Could be 3 AM due to DST shift
const in24Hours = new Date(date.getTime() + 24 * 60 * 60 * 1000);
console.log(in24Hours.getHours()); // Might be 2 AM (actual 24 hours)
Month Boundary Issues
JavaScript handles invalid dates by rolling over, which creates surprises:
const jan31 = new Date(2024, 0, 31);
jan31.setMonth(jan31.getMonth() + 1); // Add 1 month
console.log(jan31.toISOString());
// March 2nd or 3rd! (Feb doesn't have 31 days)
const mar31 = new Date(2024, 2, 31);
mar31.setMonth(mar31.getMonth() + 1); // Add 1 month
console.log(mar31.getMonth()); // 4 (May), not 3 (April has only 30 days)
Key Takeaway: Always test date arithmetic across DST boundaries and month-end dates, especially for months with different lengths. Consider whether you need calendar arithmetic (days/months) or absolute time arithmetic (milliseconds).