liveBook · Manning

Date arithmetic

As explained in Object-Oriented Software Design in C++

Date arithmetic is the computation of dates and intervals by adding, subtracting, or otherwise manipulating calendar-day values.

Date arithmetic computes dates by adding or subtracting days and finding the interval between dates. Gregorian-calendar rules make even one-day movement nontrivial: month lengths, leap years, the missing year zero, and the 1582 calendar transition all matter. section 5.3

Two implementation strategies expose the trade-off between straightforward code and efficient arithmetic:

  • Day-by-day iteration uses next_date() and previous_date() inside add_days() and days_from(). It is functional but inefficient because loops, calendar-rule calculations, comparisons, and temporary Date objects grow with the number of days. section 5.3.1
  • Julian day numbers represent each day with one integer. Adding n becomes julian + n, and the interval becomes subtraction; conversion remains necessary when exposing year, month, and day. section 5.3.2

Counting between two dates

For September 2, 2025 and April 3, 2027, days_from() produces 578; adding 578 days to the first date returns April 3, 2027. The loop version reaches this result correctly, while the Julian-number version performs the arithmetic directly.

How Object-Oriented Software Design in C++ covers it

How deep it goes
Compares loop-based and Julian-number implementations, including performance costs and representation conversions.
Examples
Demonstrates September 2, 2025 to April 3, 2027, yielding 578 days and the matching destination date.
What it assumes
Assumes basic Date objects and calendar dates while defining the Gregorian rules needed for correct computation.
What you can do after
Evaluate loop-based and Julian-number implementations and recognize their distinct performance costs.
How it connects
Connects date arithmetic with the Gregorian calendar, Julian day numbers, and implementation hiding.

Also explained in

Compare how 2 books explain date arithmetic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.