Arithmetics on calendar dates in C or C++ (add N days to given date)

Can you please tell me any good logic which works faster and have less complexity.

If this exact thing is indeed a performance critical part of your application, you’re likely doing something wrong. For the sake of clarity and correctness, you should stick to the existing solutions. Select the one that is most appropriate to your development environment.


The C approach:

#include <stdio.h>
#include <time.h>

int main()
{        
    /* initialize */
    int y=1980, m=2, d=5;    
    struct tm t = { .tm_year=y-1900, .tm_mon=m-1, .tm_mday=d };
    /* modify */
    t.tm_mday += 40;
    mktime(&t);
    /* show result */
    printf("%s", asctime(&t)); /* prints: Sun Mar 16 00:00:00 1980 */
    return 0;
}

The C++ without using Boost approach:

#include <ctime>
#include <iostream>

int main()
{        
    // initialize
    int y=1980, m=2, d=5;
    std::tm t = {};
    t.tm_year = y-1900;
    t.tm_mon  = m-1;
    t.tm_mday = d;
    // modify
    t.tm_mday += 40;
    std::mktime(&t);
    // show result
    std::cout << std::asctime(&t); // prints: Sun Mar 16 00:00:00 1980
}

The Boost.Date_Time approach:

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

int main()
{
    using namespace boost::gregorian;
    // initialize
    date d(1980,2,5);
    // modify
    d += days(40);
    // show result
    std::cout << d << '\n'; // prints: 1980-Mar-16
}

Leave a Comment