gpt4 book ai didi

c++ - 如何在 C++ 中将 struct tm 转换为 time_t

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:42:03 25 4
gpt4 key购买 nike

给定的函数是用于处理日期和时间的类的一部分。我解析的文件需要将给定的字符串数据转换为 time_t,但 mktime 不起作用。为什么?

 struct tm DateTimeUtils::makeTime(string arrTime)//accepts in format"2315"means 11.15 pm
{
struct tm neww;
string hour = arrTime.substr(0,2);
int hour_int = stoi(hour);
neww.tm_hour=hour_int;//when this is directly printed generates correct value


string minute = arrTime.substr(2,2);
int minute_int = stoi(minute);
neww.tm_min=(minute_int);//when this is directly printed generates correct value

time_t t1 = mktime(&neww);//only returns -1
cout<<t1;

return neww;

}

最佳答案

来自mktime(3) man page :

time_t ... represents the number of seconds elapsed since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).

然后你有 struct tm 的字段,尤其是这个:

tm_year

The number of years since 1900.

所以基本上,如果 tm_year 设置为 0 并且我们正确地进行数学运算,我们将得到一个 70 年差,这需要以秒表示,这可能太大了。

您可以通过将 struct tm 值初始化为 Epoch 并将其用作基本引用来解决此问题:

 struct tm DateTimeUtils::makeTime(string arrTime)//accepts in format"2315"means 11.15 pm
{
time_t tmp = { 0 };
struct tm neww = *localtime(&tmp);
string hour = arrTime.substr(0,2);
int hour_int = stoi(hour);
neww.tm_hour=hour_int;//when this is directly printed generates correct value


string minute = arrTime.substr(2,2);
int minute_int = stoi(minute);
neww.tm_min=(minute_int);//when this is directly printed generates correct value

time_t t1 = mktime(&neww);//only returns -1
cout<<t1;

return neww;
}

关于c++ - 如何在 C++ 中将 struct tm 转换为 time_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47938426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com