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

Time:11-09

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:

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?

CodePudding user response:

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";
}
  •  Tags:  
  • c
  • Related