gpt4 book ai didi

c++ - 如何正确地将 tm 转换为 time_t?

转载 作者:行者123 更新时间:2023-11-28 06:07:37 25 4
gpt4 key购买 nike

我想创建一个 tm 并用特定时间填充它,然后我想从中减去一定量的时间。

这是我目前的情况

time_t time_1, time_2;
struct tm tm;
struct tm tm2;

strptime("1 1 1900 12:43:40", "%d %m %Y %H:%M:%S", &tm);
strptime("1 1 1900 11:33:45", "%d %m %Y %H:%M:%S", &tm2);


time_1 = mktime(&tm);
time_2 = mktime(&tm2);

// time_1 = difftime(time_2, time_1);
cout << ctime(&time_1) << endl;
cout << asctime(&tm);

我正计划使用 difftime 来计算差异,但 ctime 显示的时间与 asctime 不同,我哪里出错了?

最佳答案

差异可能是由于夏令时差异造成的 - 即结构 tm 的 tm_isdst 字段。调用 ctime(t) 等同于 asctime(localtime(t)),因此尝试只调用 localtime(time_1) 并将结果逐个字段与 tm 进行比较。我还建议不要调用您的变量 tm,因为当它与结构同名时可能会造成混淆,尤其是因为这是 C++,因此 struct 关键字是可选的。

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

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