easy way to add 1 month to a time_t in C/C++

Glen picture Glen · Jan 8, 2009 · Viewed 18k times · Source

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

Answer

Pieter picture Pieter · Jan 8, 2009

You can use Boost.GregorianDate for this.

More specifically, determine the month by adding the correct date_duration, and then use end_of_month_day() from the date algorithms