I have some code that uses the Oracle function add_months to increment a Date by X number of months.
I now need to re-implement the same logic in a C / C++ function. For reasons I don't want/need to go into I can't simply issue a query to oracle to get the new date.
Does anyone know of a simple and reliable way of adding X number of months to a time_t? Some examples of the types of calculations are shown below.
30/01/2009 + 1 month = 28/02/2009
31/01/2009 + 1 month = 28/02/2009
27/02/2009 + 1 month = 27/03/2009
28/02/2009 + 1 month = 31/03/2009
31/01/2009 + 50 months = 31/03/2013
Really new answer to a really old question!
Using this free and open source library, and a C++14 compiler (such as clang) I can now write this:
And it compiles.
Note the remarkable similarity between the actual code, and the OP's pseudo-code:
Also note that compile-time information in leads to compile-time information out.
Convert
time_t
tostruct tm
, add X to month, add months > 12 to years, convert back. tm.tm_mon is an int, adding 32000+ months shouldn't be a problem.[edit] You might find that matching Oracle is tricky once you get to the harder cases, like adding 12 months to 29/02/2008. Both 01/03/2009 and 28/02/2008 are reasonable.
Method AddMonths_OracleStyle does what you need.
Perhaps you would want to replace IsLeapYear and GetDaysInMonth to some librarian methods.
You can use Boost.GregorianDate for this.
More specifically, determine the month by adding the correct
date_duration
, and then useend_of_month_day()
from the date algorithms