Question

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.

Was it helpful?

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.

OTHER TIPS

Please read the man pages, prior to coming here:

Verbatim from man mktime():

The members of the tm structure are:

tm_sec The number of seconds after the minute, normally in the range 0 to 59, but can be up to 60 to allow for leap seconds.

tm_min The number of minutes after the hour, in the range 0 to 59.

tm_hour The number of hours past midnight, in the range 0 to 23.

tm_mday The day of the month, in the range 1 to 31.

tm_mon The number of months since January, in the range 0 to 11.

tm_year The number of years since 1900.

tm_wday The number of days since Sunday, in the range 0 to 6.

tm_yday The number of days since January 1, in the range 0 to 365.

tm_isdst A flag that indicates whether daylight saving time is in effect at the time described. The value is positive if daylight saving time is in effect, zero if it is not, and negative if the information is not available.

tm_year is the number of years since 1900, not 1970.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top