How to change timestamp time_t in C?

So we can save the current time and print it with 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 before time_t tand save it back to t?

+3
source share
1 answer

time_t usually an integral type indicating seconds from an era, 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 accuracy of the time represented in clock_tand time_tare determined by implementation.

, ( , - ), , .

. , (300 ):

#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;
}

:

Sat Nov  6 10:10:34 2010
Sat Nov  6 10:15:34 2010
+4

Source: https://habr.com/ru/post/1773397/


All Articles