Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

c - add seconds to a date

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 20091231235957.

Is this possible in C?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 <time.h>
#include <stdio.h>

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
", asctime( &now_tm));
    printf( "%s
", 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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...