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

后端 未结 8 1079
误落风尘
误落风尘 2020-12-06 07:47

I have been given a date, Which I am taking as an input like (day, month, year): 12, 03, 87.

Now I need to find out the date after n days.<

相关标签:
8条回答
  • 2020-12-06 08:21

    It might be easier to do the math using seconds since the epoch instead of manipulating the date fields directly.

    For example, this program prints the date 7 days from now:

    #include <stdio.h>
    #include <time.h>
    
    main()
    {
        time_t t;
        struct tm *tmp;
    
        time(&t);
    
        /* add a week to today */
        t += 7 * 24 * 60 * 60;
    
        tmp = localtime(&t);
        printf("%02d/%02d/%02d\n", tmp->tm_mon+1, tmp->tm_mday,
            tmp->tm_year % 100);
    }
    
    0 讨论(0)
  • 2020-12-06 08:24

    The standard library mktime function includes a trick to make it easy to add a number of months or days into a given date: you can give it a date such as "45th of February" or "2nd day of the 40th month" and mktime will normalize it into a proper date. Example:

    #include <time.h>
    #include <stdio.h>
    
    int main() {
        int y = 1980;
        int m = 2;
        int d = 5;
        int skip = 40;
    
        // Represent the date as struct tm.                                                           
        // The subtractions are necessary for historical reasons.
        struct tm  t = { 0 };
        t.tm_mday = d;
        t.tm_mon = m-1;
        t.tm_year = y-1900;
    
        // Add 'skip' days to the date.                                                               
        t.tm_mday += skip;
        mktime(&t);
    
        // Print the date in ISO-8601 format.                                                         
        char buffer[30];
        strftime(buffer, 30, "%Y-%m-%d", &t);
        puts(buffer);
    }
    

    Compared to doing the arithmetic in seconds using time_t, this approach has the advantage that daylight savings transitions do not cause any problems.

    0 讨论(0)
提交回复
热议问题