add seconds to a date

后端 未结 4 1890
星月不相逢
星月不相逢 2020-12-17 15:03

I need to add seconds to a date. For example, if I have a date such as 2009127000000, I need to add the seconds to this date. Another example, add 50 seconds to 200912312359

4条回答
  •  执笔经年
    2020-12-17 15:52

    In POSIX a time_t value is specified to be seconds, however that's not guaranteed by the C standard, so it might not be true on non-POSIX systems. It commonly is (in fact, I'm not sure how often it isn't a value representing seconds).

    Here's an example of adding time values that doesn't assume a time_t represents seconds using the standard library facilities, which are really not particularly great for manipulating time:

    #include 
    #include 
    
    int main()
    {
        time_t now = time( NULL);
    
        struct tm now_tm = *localtime( &now);
    
    
        struct tm then_tm = now_tm;
        then_tm.tm_sec += 50;   // add 50 seconds to the time
    
        mktime( &then_tm);      // normalize it
    
        printf( "%s\n", asctime( &now_tm));
        printf( "%s\n", asctime( &then_tm));
    
        return 0;
    }
    

    Parsing your time string into an appropriate struct tm variable is left as an exercise. The strftime() function can be used to format a new one (and the POSIX strptime() function can help with the parsing).

提交回复
热议问题