Date Math: Common Mistakes and How to Avoid Them

Business days, month-end rollovers, leap years, and calendar calculations

Date arithmetic trips up even experienced programmers. Learn how to correctly add/subtract days, calculate business days, handle month-end rollovers, and count down to any date.

What You'll Learn

  • Adding/subtracting days, weeks, months, years
  • Month-end rollover handling
  • Leap year detection formula
  • Business days calculation (exclude weekends)
  • Day of week for any date
  • ISO 8601 week number calculation
  • Quarter determination (Q1-Q4)
  • Countdown to target date

Full Guide

Dates are deceptively complex because months have varying lengths (28-31 days), leap years add February 29, and weekends complicate business calculations. Here are the pitfalls and solutions.

Adding Days: The Basics

Start date + N days. Simple in concept, but January 31 + 1 day = February 1 (not February 31 which doesn't exist). Most date libraries handle this automatically, but spreadsheets and manual calculation often fail.

Adding Months: The Month-End Rollover Rule

  • January 31 + 1 month = February 28 (or 29)
  • April 30 + 1 month = May 30

The rule: add the months, then adjust day to max valid day for resulting month. Some systems use "last day of month" rule (Jan 31 + 1 month = Feb 28).

Leap Year Calculation Formula

Years divisible by 4 are leap years EXCEPT century years (1900, 2100) unless divisible by 400 (2000 was a leap year).

`(year % 4 == 0 && year % 100 != 0) || year % 400 == 0`

Business Days: Excluding Weekends

For a 10-business-day deadline starting Friday:

  • Day 1 = Monday
  • Day 10 = Friday of next week
  • That's 12 calendar days, not 10.

Countdown Calculation

Days until a date = target_date - today. Account for time of day: if it's 3 PM today and deadline is midnight, you have fewer "full days." For age, include the current day in the count.

ISO Week Numbers

Week 1 of a year is the week containing the first Thursday (or the week containing Jan 4). This means some dates at year start belong to the previous year's last week.