Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I modify a time_t timestamp in C?

Tags:

c

datetime

time

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?

like image 319
Lazer Avatar asked Nov 06 '10 15:11

Lazer


People also ask

How to make a timestamp in C?

The time() function is defined in time. h (ctime in C++) header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.

How does time() work in C?

C library function - time() The C library function time_t time(time_t *seconds) returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. If seconds is not NULL, the return value is also stored in variable seconds.

How to handle timestamp?

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision.


1 Answers

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
like image 51
paxdiablo Avatar answered Sep 23 '22 17:09

paxdiablo