开发者

How do I modify a time_t timestamp in C?

This is how we can store the current time and print it using time.h :

$ cat addt.c
#include<stdio.h>
#include<time.h>

void print_time(time_t tt) {
    char buf[80];
    struct tm* st = localtime(&tt);
    strftime(buf, 80, "%c", st);
    printf("%s\n", buf);
}

int main() {
    time_t t = time(NULL);
    print_time(t);
    return 0;
}
$ gcc addt.c -o addt
$ ./addt
Sat Nov  6 15:55:58 2010
$

How开发者_开发知识库 can I add, for example 5 minutes 35 seconds to time_t t and store it back in t?


time_t is usually an integral type indicating seconds since the epoch, so you should be able to add 335 (five minutes and 35 seconds).

Keep in mind that the ISO C99 standard states:

The range and precision of times representable in clock_t and time_t are implementation-defined.

So while this will usually work (and does so on every system I've ever used), there may be some edge cases where it isn't so.

See the following modification to your program which adds five minutes (300 seconds):

#include<stdio.h>
#include<time.h>

void print_time(time_t tt) {
    char buf[80];
    struct tm* st = localtime(&tt);
    strftime(buf, 80, "%c", st);
    printf("%s\n", buf);
}

int main() {
    time_t t = time(NULL);
    print_time(t);
    t += 300;
    print_time(t);
    return 0;
}

The output is:

Sat Nov  6 10:10:34 2010
Sat Nov  6 10:15:34 2010
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜