I'm having some trouble with mktime giving me the correct Unix time stamp for some arbitrary time. After a bit of trial and error, I discovered that mktime behaves properly if I give it a pointer to a struct tm on the heap, but behaves inconsistently badly when given a reference to a stack variable. To help illustrate this, here is my code:
#include <iostream>
#include <sys/time.h>
int main(void)
{
struct tm timeStruct;
timeStruct.tm_year = 110;
timeStruct.tm_mon = 10;
timeStruct.tm_mday = 26;
timeStruct.tm_hour = 0;
timeStruct.tm_min = 10;
timeStruct.tm_sec = 0;
time_t resultUnix1 = mktime(&timeStruct);
std::cout << "resultUnix1 = " << resultUnix1 << std::endl;
struct tm * timeStructPtr = new tm;
timeStructPtr->tm_year = 110;
timeStructPtr->tm_mon = 10;
timeStructPtr->tm_mday = 26;
timeStructPtr->tm_hour = 0;
timeStructPtr->tm_min = 10;
timeStructPtr->tm_sec = 0;
time_t resultUnix2 = mktime(timeStructPtr);
std::cout << "resultUnix2 = " << resultUnix2 << std::endl;
return 0;
}
And here is the output from two sample runs of the same code:user@lucidlynx:~/Development$ ./mktime resultUnix1 = 1290744600 resultUnix2 = 1290744600 user@lucidlynx:~/Development$ ./mktime resultUnix1 = 1290741000 resultUnix2 = 1290744600The second call, the one with the pointer, always returns the correct value. But the first call, the one passing a reference to the struct instead, seems to return the correct value about half of the time and an incorrect value (an hour earlier interestingly enough) the other half. It also changes the tm_mday, tm_hour, etc, from the timeStruct object passed in, to be consistent with the wrong unix timestamp it returned to me.
I'm at a lost to explain this behavior. Ideas anyone? I'm running my test program on Ubuntu 10.04 64-bit, Linux kernel 2.6.32-25-generic
Thanks!


Sign In
Create Account


Back to top









