c - Difftime 一直返回 0

标签 c mktime

一开始我想强调一下,我已经阅读了 stack overflow 中所有类似的帖子。没有任何帮助。

#include <stdio.h>
#include <stdlib.h>
#define _USE_32BIT_TIME_T 1
#include <time.h>

int main(void)
{
  struct tm beg;
  struct tm aft;
  beg.tm_hour=0; beg.tm_min=0; beg.tm_sec=0;
  aft.tm_hour=11; aft.tm_min=19; aft.tm_sec=19;
  long long c;
  c=difftime(mktime(&aft),mktime(&beg));
  printf("%lld",c);
  return 0;
 }

所有 timr 都打印出 0,但当我尝试将 mktime(&aft) 更改为 time now time(&now) 时,我得到了非零结果。我应该在此代码中更正什么?

最佳答案

如果传递给 mktime 的参数引用 1970 年 1 月 1 日午夜之前的日期,或者如果无法表示日历时间,则该函数返回 –1 转换为类型 time_t。 ( http://msdn.microsoft.com/en-us/library/aa246472(v=vs.60).aspx )

这可能导致 mktime 失败,因为 beg 和 aft 中的 tm_year 变量无效。

将此变量设置为代表 1970 年之后的一年的值会产生预期的结果。

#include <stdio.h>
#include <stdlib.h>
#define _USE_32BIT_TIME_T 1
#include <time.h>

int main(void)
{
    struct tm beg = {0};
    struct tm aft = {0};

    beg.tm_hour=0; beg.tm_min=0; beg.tm_sec=0;
    beg.tm_year = 71;  //Set to 1971

    aft.tm_hour=11; aft.tm_min=19; aft.tm_sec=19;
    aft.tm_year = 71;  //Set to 1971

    long long c;
    c=difftime(mktime(&aft),mktime(&beg));
    printf("%lld",c);
        return 0;
}

关于c - Difftime 一直返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24381575/

相关文章:

c - 字符数组中的递归函数,用于在数组的前 3 个元素中查找辅音

c++ - 转换为 unix 时间戳不正确

c - mktime 返回错误的时间戳(关闭整整一个月)

php - mktime、date() 或 mysql 时间戳用于预测?

c - else if 语句阻止程序检测最大索引

从 Lua 通过 Swig 调用 C 函数指针

c - 有没有使用 bool 值的标准方法?因为我的代码出错了

c++ - 获取自 C++ 纪元以来的天数(跨平台)

c++ - difftime 和 strftime 值中的差异

c - 使用 Qt Creator(不使用任何类型的 Qt 框架)时的 C(非 C++)程序的 printf