C++使用timegm转换UTC日期字符串时月份自动递增问题
UTC日期字符串转时间戳时月份自动递增的问题
输入UTC日期字符串“20221222074648”(对应2022-12-22 07:46:48),生成的时间戳1674373608实际对应2023-01-22 07:46:48,其他部分转换正常,但月份自动递增了1,代码中未主动修改月份变量:
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++标准库的struct tm中,tm_mon字段是从0开始计数的:0代表1月,1代表2月……11代表12月。你直接把字符串中提取的12赋值给tm_mon,相当于告诉系统当前是第13个月,timegm函数会自动执行日期归一化,将“13月”转换为下一年的1月,最终导致时间戳对应的月份递增了1。
解决方案
将提取到的月份值减1后再赋值给tm_mon,修改后的代码行如下:
t.tm_mon = stoi(receivedDate.substr(4, 2), &other_size, 10) - 1;
这样输入12时,tm_mon会被设置为11,对应实际的12月,timegm就能生成正确的时间戳了。
内容的提问来源于stack exchange,提问作者Lazouache Farid
相关产品推荐
相关产品推荐

