Search code examples
cmktime

Why does mktime give me an hour less?


I would like to see if at 00:00:00 on January 1, 1970 it actually corresponds to 0 seconds, and I wrote the following:

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

int main(void) {
    int year = 1970;
    
    struct tm t = {0};
    
    t.tm_mday = 1; // January
    t.tm_year = year - 1900;
    t.tm_hour = 0;
    t.tm_isdst = -1;
    
    printf("%ld\n", mktime(&t));
    
    return 0;
}

it gives me a value of -3600. Where am I wrong?

PS: tested with GCC v.10.1. I tried with another compiler under another architecture and it gives me back the correct value.


Solution

  • The time info you provide to mktime() is in local time, so the timezone matters even if summer time / daylight savings time does not.

    You can fool your program by telling it you're in UTC:

    $ gcc mytime.c -o mytime
    $ ./mytime
    28800          <-- Pacific time in the US
    $ TZ=GMT0 ./mytime
    0