提问人:Lazouache Farid 提问时间:7/26/2022 更新时间:7/27/2022 访问量:135
在 C++ 中使用 mktime 和 timegm 函数的月份自动增量
Month auto increment using mktime and timegm functions in C++
问:
我想使用 C++ 将字符串日期 (UTC) 转换为时间戳。 它工作正常,除了月份,它会自动递增 1。
如果字符串为 ,则时间戳将为 ,即 的时间戳。20221222074648
2022-12-22 07:46:48
1674373608
2023-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);
答:
1赞
Simon Marolleau
7/27/2022
#1
你的问题很简单!
从 0 到 11,您需要在月份值上添加 -1tm.tm_mom
t.tm_mon = stoi(receivedDate.substr(4, 2), &other_size, 10) - 1;
评论
t.tm_mon
从 0(1 月)变为 11(12 月)。但是你把 12 个放进去。