Skip to content

3.5 difference of two dates

Marshall Clow edited this page May 15, 2013 · 1 revision

Problem

Given two dates, you want know how many days they differ by

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

//  Difference between two dates    
    date_duration dur3 = d2 - d1;
    std::cout << "Date difference: " << dur3.days() << std::endl;
    
    return 0;
    }

When you run this, you should get the output:

Date difference: 94
Clone this wiki locally