Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does mktime give me an hour less?

Tags:

c

mktime

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.

like image 841
Roberto Rocco Avatar asked Jul 12 '20 23:07

Roberto Rocco


Video Answer


2 Answers

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
like image 130
Steve Friedl Avatar answered Sep 21 '22 22:09

Steve Friedl


The mktime function takes a time in local time. Apparently, 00:00:00 at your local time was one hour before the epoch. Launch the program with TZ set to UTC.

like image 42
David Schwartz Avatar answered Sep 17 '22 22:09

David Schwartz