Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Weird behaviour in strptime and mktime, 01-01-1970 (d-m-Y) is unix timestamp 354907420?

I have some weird behaviour in strptime and mktime on MacOS. Perhaps I am doing something wrong but I am getting some weird output.

This the code.

int main(int argc, const char * argv[]) {
    const char* timestamp = "01-01-2022";
    const char* format = "%d-%m-%Y";
    struct tm tm;
    if (strptime(timestamp, format, &tm) == NULL) {
        return -1;
    }
    time_t x = mktime(&tm);
    std::cout << x << "\n";
}

Which generates the following output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1995902620

Which is Thu Mar 31 2033 17:23:40 GMT+0000.

When I edit the timestamp to 01-01-1970 the program outputs 354907420.

What am I doing wrong here?

>Solution :

tm is uninitialized; you should initialize it before calling strptime(). This program works:

#include <iostream>
#include <ctime>

int main(int argc, const char * argv[]) {
    const char* timestamp = "01-01-1970";
    const char* format = "%d-%m-%Y";
    struct tm tm = {};
    if (strptime(timestamp, format, &tm) == NULL) {
        return -1;
    }
    time_t x = mktime(&tm);
    std::cout << x << "\n";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading