In this article we will discuss how to add or subtract days, months & Years from a date object.

Add / Subtract Days from a Date

For example, if current date is 21 March 2016. Then subtracting 100 days from this date will make the date 12 Dec 2015

For this we will use type boost::gregorian::days to represent days i.e.

Now we can add or subtract this days object from the date object. So, lets subtract 10 days from a Date object i.e.

It will make the date to point to 12 Dec 2015.

Add / Subtract Months from a Date

Adding 2 months to date 12 Dec 2015 will make the date 12 Feb 2016

For this we will use type boost::gregorian::months to represent days i.e.

Now we can add or subtract this from the date object. So, lets add 2 months in the date object i.e.

It will make the date to point to 12 Feb 2016.

Add / Subtract Years from a Date

Subtracting 3 Years to date 12 Feb 2016 will make the date 12 Feb 2013

For this we will use type boost::gregorian::years to represent days i.e.

Now we can add or subtract this from the date object. So, lets subtract 2 months in the date object i.e.

It will make the date to point to 12 Feb 2013.

Complete Example

Let’s see the complete example,

Output:

To compile this example use following command in linux,

g++ –std=c++11 example.cpp -lboost_date_time