c++timectime

Coming dates in C++


I have the following code, with which I get today's date. I would like to know if from this code I can obtain the date 6 and 12 months later. Or how can I get these dates?

Thank you!

#include <iostream>
#include <ctime>

using namespace std;

int main() {
    time_t hoy = time(0);
    char* fecha = ctime(&hoy);
    
    cout << "La fecha es: " << fecha << endl;
}

I try to make a program with which the user planned the fertilization period of certain plants, among other things, that is why I try to make the program print the date of the next 6 and 12 months, from today (well, from the day in which the user registers a plant). So far I have not succeeded. :(


Solution

  • If you want 6 months from a given date, counting months and not days, the solution is to split the date and increment manually the months and years. Then you will have to adjust for year wrapping and month wrapping as well.

    These functions are defined in C89/C99 so not specific to Posix.

    The biggest advantage of this solution is that you don't have to link against any external library. It should be available with your compiler on Linux, Mac and even on Windows/MS Visual Studio.

    #include <time.h>
    #include <stdint.h>
    #include <stdio.h>
    
    time_t add_months( time_t from_date, uint32_t months ) {
        // Split date
        struct tm* tmptr = ::gmtime( &from_date );
        if ( tmptr == nullptr ) return 0;
        struct tm date = *tmptr;
    
        // Save original date
        struct tm org = date;
    
        // Add months/years
        uint32_t years = months/12;
        months = months % 12;
        date.tm_year += years;
        date.tm_mon += months;
    
        // Correct for year wrap
        if ( date.tm_mon>11 ) { 
            date.tm_mon -= 12;
            date.tm_year += 1;
        }
    
        // Convert back to time_t
        time_t dt = mktime( &date );
    
        // Check for end of month wrap
        // eg Jan/30 -> Mar/02 -> Feb/28
        if ( date.tm_mday != org.tm_mday ) {
            dt -= date.tm_mday * 86400;
        }
        return dt;
    }
    
    int main() {
        time_t now = time(nullptr);
        time_t later = add_months( now, 6 );
    
        struct tm* tmptr = ::gmtime( &now );
        if ( tmptr!=nullptr ) {
            printf( "Now: %s\n", asctime(tmptr));
        }
        tmptr = ::gmtime( &later );
        if ( tmptr!=nullptr ) {
            printf( "Later: %s\n", asctime(tmptr));
        }
    }
    

    Result:

    Program stdout
    Now: Thu Jan  6 01:47:07 2022
    Later: Wed Jul  6 01:47:07 2022
    

    Godbolt: https://godbolt.org/z/vE4xhsP3E