在 C++ 中使用 mktime 和 timegm 函数的月份自动增量

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

提问人:Lazouache Farid 提问时间:7/26/2022 更新时间:7/27/2022 访问量:135

问:

我想使用 C++ 将字符串日期 (UTC) 转换为时间戳。 它工作正常,除了月份,它会自动递增 1。

如果字符串为 ,则时间戳将为 ,即 的时间戳。202212220746482022-12-22 07:46:4816743736082023-01-22 07:46:48

我不明白这种自动递增的原因,因为下面的代码中没有月份变量的变化。

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

C++ C++11 时间戳 mktime

评论

1赞 Pepijn Kramer 7/26/2022
不知道为什么你会得到这个错误,但为什么不使用<chrono>它是一个完整的stl库,用于与时间相关的任何内容。对于 C++20,它具有日期时间解析功能。
4赞 Eljay 7/26/2022
t.tm_mon从 0(1 月)变为 11(12 月)。但是你把 12 个放进去。
1赞 Mgetz 7/26/2022
相关解答

答:

1赞 Simon Marolleau 7/27/2022 #1

你的问题很简单! 从 0 到 11,您需要在月份值上添加 -1tm.tm_mom

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