Skip to content

3.4 adding to or subtracting from a date

Marshall Clow edited this page May 15, 2013 · 2 revisions

Problem

You want to add or subtract a number of days from a date

Solution:

Using Boost date-time this can be easily achieved.

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <ctime>

using namespace boost::posix_time;
using namespace boost::gregorian;

int main ( int, char ** ) {
    date d1 ( 2013, 4, 1 );   // April Fool's Day
    date d2 ( 2013, 7, 4 );   // Fourth of July

//  Adding to a date
    date d3 = d1 + days(34);
    date d4 = d2 - days(60);
    std::cout << "April Fool's + 34: " << d3 << std::endl;
    std::cout << "4th of July  - 60: " << d4 << std::endl;
    std::cout << std::endl;

    return 0;
    }

When you run this, you should get the output:

April Fool's + 34: 2013-May-05
4th of July  - 60: 2013-May-05
Clone this wiki locally