Question

I want to add delay in second to time in format struct "tm" so I run this code :

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

#define SEC_PER_DAY 86400

#define SEC_PER_HR 3600

#define SEC_PER_MIN 60

int main(void) {
    time_t     now;
    time_t     time_delay;
    struct tm *ts;
    struct tm *ts_delay;
    char       buf[140];
    char       buf_delay[140];
    now = time(NULL);
    int delay =100;

    ts_delay = localtime(&now);

    printf("day = %d \n",ts_delay->tm_mday);
    ts_delay->tm_mday += delay /SEC_PER_DAY;
    printf("day = %d \n",ts_delay->tm_mday);
    printf("hour = %d \n",ts_delay->tm_hour);
    ts_delay->tm_hour += (delay%SEC_PER_DAY)/SEC_PER_HR;
    printf("hour = %d \n",ts_delay->tm_hour);
    printf("min = %d \n",ts_delay->tm_min);
    ts_delay->tm_min += ((delay%SEC_PER_DAY)%SEC_PER_HR)/SEC_PER_MIN;
    printf("min = %d \n",ts_delay->tm_min);
    printf("sec = %d \n",ts_delay->tm_sec);
    ts_delay->tm_sec += ((delay%SEC_PER_DAY)%SEC_PER_HR)%SEC_PER_MIN;
    printf("sec = %d \n",ts_delay->tm_sec);

    /* Format and print the time, "ddd yyyy-mm-dd hh:mm:ss zzz" */
    ts = localtime(&now);


    strftime(buf, sizeof(buf), "%FT%T%z", ts);
    strftime(buf_delay, sizeof(buf_delay), "%FT%T%z", ts_delay);
    puts(buf);
    puts(buf_delay);
    return 0; 
}

the result :

day = 6
day = 6
hour = 4
hour = 4
min = 14
min = 15
sec = 24
sec = 64
2013-12-06T04:14:24-0600 ==> ts
2013-12-06T04:14:24-0600 ==> ts_delay

it seems that delay is not added to ts_delay !!

any push to the right direction would be very helpful thx

Was it helpful?

Solution

Your struct tm * ts_delay gets overwritten by the 2. call to localtime() You have this code:

ts_delay = localtime(&now);
... change ts_delay;
ts = localtime(&now);

Now, localtime() returns a pointer. So some storage have to be allocated so the return value of localtime can point somwhere valid. The runtime will allocate that storage in a single static buffer (perhaps per thread) for the result of localtime(). So the 2. call to localtime() will overwrite the same buffer that ts_delay points to.

Instead copy the result of localtime() into storage that you manage yourself, instead of using a struct tm pointer into the single available buffer.

struct tm ts;      //not a pointer anymore
struct tm ts_delay;

ts_delay = *localtime(&now); //copy the returned struct
... change ts_delay;
ts = *localtime(&now);

Or use getlocaltime_r if your platform provides it, e.g.

localtime_r(&now, &ts);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top