Algorithm to add or subtract days from a date?

bcoughlan picture bcoughlan · Feb 26, 2010 · Viewed 62k times · Source

I'm trying to write a Date class in an attempt to learn C++.

I'm trying to find an algorithm to add or subtract days to a date, where Day starts from 1 and Month starts from 1. It's proving to be very complex, and google doesn't turn up much,

Does anyone know of an algorithm which does this?

Answer

Mark Ransom picture Mark Ransom · Feb 26, 2010

The easiest way is to actually write two functions, one which converts the day to a number of days from a given start date, then another which converts back to a date. Once the date is expressed as a number of days, it's trivial to add or subtract to it.

You can find the algorithms here: http://alcor.concordia.ca/~gpkatch/gdate-algorithm.html