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?
I would suggest writing first a routine which converts year-month-day into a number of days since fixed date, say, since 1.01.01. And a symmetric routine which would convert it back.
Don't forget to process leap years correctly!
Having those two, your task would be trivial.
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
One approach is to map the date to the Julian number of the date, do your integer operations and then transform back.
You will find plenty of resources for the julian functions.
You don't really need an algorithm as such (at least not something worthy of the name), the standard library can do most of the heavy lifting; calender calculations are notoriously tricky. So long as you don't need dates earlier than 1900, then:
Example usage:
I know this is a very old question but it's an interesting and some common one when it comes to working with dates and times. So I thought of sharing some code which calculates the new date without using any inbuilt time functionality in C++.
Try this function. It correctly calculates additions or subtractions. dateTime argument must be in UTC format.
And there are example of using: