Search code examples
c++timezonemktime

Strange mktime behaviour - Change if return value is assigned to a variable


I'm experimenting a strange mktime() function behaviour. When I assign the value returned by the function, the value of the input parameter is one and when I doesn't the value is different.

I already know that mktime() adjust the values of the struct tm input parameter but what's happening it's different, lets see the code with the corresponding output:

First code

#include <iostream>
#include <time.h>

using namespace std;

int main(int argc, char** argv) {
    struct tm cT;
    strptime("31/07/2014 16:54:00", "%d/%m/%Y%n%T", &cT);
    mktime(&cT);

    cout << "Current Time: "  << cT.tm_mday << "/" << cT.tm_mon + 1 << "/" << cT.tm_year + 1900 << " " << cT.tm_hour << ":" << cT.tm_min << ":" << cT.tm_sec << endl;

}

Output:

Current Time: 31/7/2014 16:54:0

Second code

#include <iostream>
#include <time.h>

using namespace std;

int main(int argc, char** argv) {
    struct tm cT;
    strptime("31/07/2014 16:54:00", "%d/%m/%Y%n%T", &cT);
    time_t t = mktime(&cT);

    cout << "Current Time: "  << cT.tm_mday << "/" << cT.tm_mon + 1 << "/" << cT.tm_year + 1900 << " " << cT.tm_hour << ":" << cT.tm_min << ":" << cT.tm_sec << endl;

}

Output:

Current Time: 31/7/2014 15:54:0

Any help is welcome. :)


Solution

  • This is a classic case of forgetting to initialize a variable. Specifically, you need to initialize the cT variable with appropriate values for at least all fields that won't be touched by strptime (strptime will only set those fields corresponding to the input field descriptors in the format string).

    Eg. :

    struct tm cT = { 0 };
    cT.tm_isdst = -1;
    strptime("31/07/2014 16:54:00", "%d/%m/%Y%n%T", &cT);