Search code examples
cmktimetime-t

Converting human time to epoch Unix time returning negative number


I am currently working on some C code and I am trying to convert a human readable date into an epoch time stamp (unix timestamp). However, its always returning a negative number. I'm using struct tm and hard coding the values of the date until I get it working properly. Below is the code

struct tm t;
time_t t_of_day;
t.tm_year = 2012 - 1970;
t.tm_mon = 9;
t.tm_mday = 24;
t.tm_hour = 11;
t.tm_min = 34;
t.tm_sec = 30;
t.tm_isdst = 1;
t_of_day = mktime(&t);
printf("Epoch time stamp is: %ld\n", t_of_day);

When this code executes I get the output of -858000330.

Thanks for any help you can provide.


Solution

  • 2012 - 1970 computes to 42. And year 1942 is before 1/1/1970. That is normal that mktime() result into a negative timestamp though.

    from mktime man page:

    tm_year   The number of years since 1900.
    

    change your year calculation to 2012 - 1900 and you should be fine.