stumped
stumped

Reputation: 3293

Time functions in C?

I have to find the date 4,000,000 seconds from now. I can get the correct answer if I add 4,000,000 to secondsSince1970, but I was wondering why it doesn't work if I add 4,000,000 to now.tm_sec?

int main(int argc, const char * argv[])
{
    long secondsSince1970 = time(NULL) + 4000000;

    struct tm now;

    localtime_r(&secondsSince1970, &now);

    printf("The date from 4,000,000 seconds from now is %i-%i-%i\n", now.tm_mon + 1, now.tm_wday, now.tm_year + 1900);
}

Output: The date is 10-1-2012


int main(int argc, const char * argv[])
{
    long secondsSince1970 = time(NULL);

    struct tm now;

    localtime_r(&secondsSince1970, &now);
    now.tm_sec += 4000000;

    printf("The date from 4,000,000 seconds from now is %i-%i-%i\n", now.tm_mon + 1, now.tm_wday, now.tm_year + 1900);
}

Output: The date is 8-4-2012

Upvotes: 1

Views: 516

Answers (3)

D.Shawley
D.Shawley

Reputation: 59633

Adding a value to tm_sec is simply changing the integer member of now. The easiest way to do what you are trying to do is to pass the struct tm into mktime to convert it back into a time_t. Then call localtime_r on the resulting value.

void
add_seconds(struct tm* broken, int num_seconds) {
   time_t then;
   broken->tm_sec += num_seconds;
   then = mktime(broken);
   localtime_r(&then, broken);
}

int
main(int argc, char const* argv[]) {
    time_t secondsSince1970 = time(NULL);
    struct tm now;
    localtime_r(&secondsSince1970, &now);
    add_seconds(&now, 4000000);
    printf("The date at 4,000,000 seconds from now is %i-%i-%i\n",
           now.tm_mon + 1, now.tm_mday, now.tm_year + 1900);
    return EXIT_SUCCESS;
}

Upvotes: 2

user1202136
user1202136

Reputation: 11567

It is incorrect to do this:

now.tm_sec += 4000000;

You tm_sec needs to be between 0 and 59 (60 for leap second).

You would need to do something like:

now.tm_sec += 4000000;
now.tm_min += now.tm_sec / 60; now.tm_sec %= 60;
now.tm_hour += now.tm_min / 60; now.tm_min %= 60;
etc.

Upvotes: 0

hmakholm left over Monica
hmakholm left over Monica

Reputation: 23342

Your struct tm is just a bunch of variables that get filled in by localtime_r. After the call to localtime_r, assigning to one of these variables will not magically make the other ones change their values.

Upvotes: 5

Related Questions