Search code examples
c++datec++11boosttime

C++ Days between given date and today´s date


I have a function called int differenceDatesInDays(string& date). This function should get a string value as a date (YYYY-MM-DD) and compare it with today´s date.

I don´t know if there is already something inside the STL, i could not find a matching algorithm. I just found out that boost has a solution for this, but i don´t want to use boost.

So, this is my code so far:

int differenceDatesInDays(string& date) {
    string year = date.substr(0, 4);
    string month = date.substr(5,2);
    string day = date.substr(8, string::npos);

    int y = stoi(year);
    int m = stoi(month);
    int d = stoi(day);

    time_t time_now = time(0);
    tm* now = localtime(&time_now);

    int diffY = y - (now->tm_year + 1900);
    int diffM = m - (now->tm_mon + 1);
    int diffD = d - (now->tm_mday);

    int difference = (diffY * 365) + (diffM * 30) + diffD;

    return difference;
}

I don´t know how to find out if the month has 30, 31 or 28 days.


Solution

  • Something along these lines, perhaps:

    int differenceDatesInDays(string& date) {
        // Parse `date` as in your code
        int y = ...;
        int m = ...;
        int d = ...;
    
        tm then = {0};
        then.tm_year = y - 1900;
        then.tm_mon = m - 1;
        then.tm_day = d;
        time_t then_secs = mktime(&then);
    
        time_t time_now = time(0);
        tm* now = localtime(&time_now);
        tm today = {0};
        today.tm_year = now->tm_year;
        today.tm_mon = now->tm_mon;
        today.tm_day = now->tm_day;
        time_t today_secs = mktime(&today);
    
        return (today_secs - then_secs) / (24*60*60);
    }