mardi 26 juillet 2022

Month auto increment using mktime and timegm functions in C++

I'd like to convert a string date (UTC) to a timestamp using C++. It works fine except for the month, which is auto incremented by one.

If the string is 20221222074648, for 2022-12-22 07:46:48, the timestamp will be 1674373608, which is the timestamp of 2023-01-22 07:46:48.

I don't understand the reason of this auto-increment, because there's no changes of the month's variable in the code below.

    cout << "date : " << receivedDate << endl;
    struct tm t;
    time_t timestamp;
    size_t year_size = 4;
    size_t other_size = 2;
    t.tm_year = stoi(receivedDate.substr(0, 4), &year_size, 10) - 1900;
    t.tm_mon = stoi(receivedDate.substr(4, 2), &other_size, 10);
    t.tm_mday = stoi(receivedDate.substr(6, 2), &other_size, 10);
    t.tm_hour = stoi(receivedDate.substr(8, 2), &other_size, 10);
    t.tm_min = stoi(receivedDate.substr(10, 2), &other_size, 10);
    t.tm_sec = stoi(receivedDate.substr(12, 2), &other_size, 10);
    t.tm_isdst = -1;
    cout << "year : " << t.tm_year + 1900 << "\nmonth : " << t.tm_mon << "\nday : " << t.tm_mday << "\nhour : " << t.tm_hour << "\nminutes : " << t.tm_min << "\nseconds : " << t.tm_sec << endl;

    timestamp = timegm(&t);

    cout << "timestamp : " << timestamp << endl;
    cout << "asctime timestamp : " << asctime(&t);

Aucun commentaire:

Enregistrer un commentaire