0

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);

  • 1
    Not sure why you get this error, but why not use [](https://en.cppreference.com/w/cpp/chrono) it is a full stl library for anything related to time. And for C++20 it has date time parsing functions. – Pepijn Kramer Jul 26 '22 at 14:06
  • 4
    `t.tm_mon` goes from 0 (Jan) to 11 (Dec). But you're putting 12 in there. – Eljay Jul 26 '22 at 14:11
  • 1
    [Related](https://stackoverflow.com/a/49941336) answer – Mgetz Jul 26 '22 at 14:39

1 Answers1

1

Your problem is pretty simple ! the tm.tm_mom goes from 0 to 11, You need to add -1 on your month value

t.tm_mon = stoi(receivedDate.substr(4, 2), &other_size, 10) - 1;