[英]How do I correctly convert from tm to time_t?
I want to create a tm and fill it with a specific time, then I want to subtract a certain amount of time from it. 我想创建一个tm并用特定的时间填充它,然后我想从中减去一定的时间。
This is what I have so far 这就是我到目前为止
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);
I was planning on using difftime to calculate the difference, but ctime isn't displaying the same time as asctime, where am I going wrong? 我打算使用difftime来计算差异,但是ctime与asctime的显示时间不同,我在哪里出错?
The difference is likely to be due to daylight saving time differences - ie the tm_isdst field of the struct tm. 该差异可能是由于夏令时差异引起的,即结构tm的tm_isdst字段。 The call ctime(t) is equivalent to asctime(localtime(t)), so try calling just localtime(time_1) and compare the result, field by field, to tm.
调用ctime(t)等效于asctime(localtime(t)),因此请尝试仅调用localtime(time_1)并将结果逐字段与tm进行比较。 I would also advise not calling your variable tm as it can be confusing when it's the same name as the struct, especially as this is C++ and therefore the struct keyword is optional.
我还建议不要调用您的变量tm,因为当它与struct同名时可能会造成混淆,尤其是因为它是C ++,因此struct关键字是可选的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.