Skip to content

Adding a number of days to a calendar date

Question

Design an algorithm that takes a date and an integer nn and returns the date nn days later, getting leap years right including the century exceptions.

Short answer

Convert to a serial day count, add nn, convert back. A year is leap if divisible by 44, except century years, which are leap only if divisible by 400400 (so 1900 is not, 2000 is). Map the date to days since a fixed epoch (whole years, then months via a cumulative table, then days), add nn, and invert by stepping or with a closed form; this avoids error-prone month-by-month loops and handles negative nn too.

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q5.5, p.158; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question