【问题标题】:difftime returns strange value on particular date [closed]difftime 在特定日期返回奇怪的值 [关闭]
【发布时间】:2015-01-03 11:46:45
【问题描述】:

我不明白为什么 difftime 返回一个奇怪的值,所以这是我正在使用的数据集和代码。

代码:

struct tm currentTime;
currentTime.tm_year = 2014 - 1900;
currentTime.tm_mon = 9 - 1;
currentTime.tm_mday = 6;
currentTime.tm_hour = 23;
currentTime.tm_min = 59;
currentTime.tm_sec = 0;
currentTime.tm_wday = 7 - 1;

struct tm previousTime;
previousTime.tm_year = 2014 - 1900;
previousTime.tm_mon = 9 - 1;
previousTime.tm_mday = 6;
previousTime.tm_hour = 23;
previousTime.tm_min = 58;
previousTime.tm_sec = 0;
previousTime.tm_wday = 7 - 1;

cout << difftime(mktime(&currentTime), mktime(&previousTime)) << endl;

这打印:

3660

任何想法为什么我得到这个值? 我应该得到 60,因为相差一分钟。 我尝试了其他一些值,它们都有效.. 我正在将 CodeBlocks 与 mingw 一起使用。

编辑:答案:使用 tm_isdst 解决了问题!血腥夏令时:P

struct tm currentTime;
currentTime.tm_year = 2014 - 1900;
currentTime.tm_mon = 9 - 1;
currentTime.tm_mday = 6;
currentTime.tm_hour = 23;
currentTime.tm_min = 59;
currentTime.tm_sec = 0;
currentTime.tm_wday = 7 - 1;
currentTime.tm_isdst = - 1;

struct tm previousTime;
previousTime.tm_year = 2014 - 1900;
previousTime.tm_mon = 9 - 1;
previousTime.tm_mday = 6;
previousTime.tm_hour = 23;
previousTime.tm_min = 58;
previousTime.tm_sec = 0;
previousTime.tm_wday = 7 - 1;
previousTime.tm_isdst = - 1;

cout << difftime(mktime(&currentTime), mktime(&previousTime)) << endl;

【问题讨论】:

  • 除了不能编译because the member names are incorrect,一旦你修复了错误you get 60 as expected.。 tl;博士;无法复制。
  • 它更有可能与时区有关。您是否注意到您的输出与您想要的结果相差一天?
  • 夏令时问题?
  • 你的约会对象是否跨越夏令时边界?
  • @Hawknight 初始化两个变量的tm_isdst 字段,看看会发生什么

标签: c++ c time mingw ctime


【解决方案1】:

在调用mktime()之前,通常需要设置struct tm的7个字段。由于 OP 只设置了其中的 6 个,未初始化的数据位于字段 tm_isdst 中,导致 3600 秒的意外变化。

struct tm currentTime;
currentTime.tm_year = 2014 - 1900;
currentTime.tm_mon = 9 - 1;
currentTime.tm_mday = 6;
currentTime.tm_hour = 23;
currentTime.tm_min = 59;
currentTime.tm_sec = 0;

currentTime.tm_isdst = -1;  // **
// currentTime.tm_wday = 7 - 1; 

mktime(&currentTime);

建议将struct tm 填零,如struct tm currentTime = { 0 }; 以确保所有字段都指定为struct tm 可能包含除9 之外的字段:int tm_sec tm_min tm_hour tm_mday tm_mon tm_year tm_wday tm_yday tm_isdst


注意事项:

tm_wdaytm_yday 中的原始值被 mktime() 忽略并重新计算。其他字段的原始值不限制在正常范围内,也会重新计算。

** tm_isdst 的正值或零值导致mktime 函数最初分别假定夏令时在指定时间内有效或无效。负值会导致它尝试确定夏令时是否在指定时间内有效。

【讨论】:

  • 这里有很好的解释。基本上,在使用之前将变量填零更安全?
  • @Hawknight 由于struct tm 至少有定义明确的 9 个字段,因此可移植代码不应该冒险让其他代码未初始化。一般来说,当使用非你制作的结构时,最好在使用前将它们归零。如果您的代码填零,除了接近 DST 班次外,一切都会如预期的那样。无需深入挖掘,当您知道设置时使用tm_isdst = 0 or 1,否则使用-1
猜你喜欢
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多