Lazer
Lazer

Reputation: 95020

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?

Upvotes: 5

Views: 9089

Answers (1)

paxdiablo
paxdiablo

Reputation: 882756

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

Upvotes: 5

Related Questions