6

我试图通过使用下面的 C 代码来获得两个日期之间的差异。

但是代码总是给出差异0。帮助我找出我犯错的地方。

我在linux下使用gcc编译器。

#include <stdio.h>  
#include <time.h>       
int main ()
{
  struct tm start_date;
  struct tm end_date;
  time_t start_time, end_time;
  double seconds;

  start_date.tm_hour = 0;  start_date.tm_min = 0;  start_date.tm_sec = 0;
  start_date.tm_mon = 10; start_date.tm_mday = 15; start_date.tm_year = 2013;

  end_date.tm_hour = 0;  end_date.tm_min = 0;  end_date.tm_sec = 0;
  end_date.tm_mon = 10; end_date.tm_mday = 20; end_date.tm_year = 2013;

  start_time = mktime(&start_date);
  end_time = mktime(&end_date);

  seconds = difftime(end_time, start_time);

  printf ("%.f seconds difference\n", seconds);

  return 0;
}

编辑: @qchen 的回答对解决我的问题很有帮助。还有一个疑问。以下是我的更新。从答案

  start_date.tm_hour = 0;  start_date.tm_min = 0;  start_date.tm_sec = 0;
  start_date.tm_mon = 10-1; start_date.tm_mday = 18; start_date.tm_year = 2013-1876;

  end_date.tm_hour = 0;  end_date.tm_min = 0;  end_date.tm_sec = 0;
  end_date.tm_mon = 10-1; end_date.tm_mday = 20; end_date.tm_year = 2013-1876;

tm_year 是自 1900 年以来的年份,那么如果我将 1876 替换为 1876 到 2012 之间的年份,为什么我会得到正确的输出。

4

3 回答 3

3

问题是 tm_year 是 1900 年以来的年份,所以 2013 年将是 113 http://en.cppreference.com/w/cpp/chrono/c/tm

  start_date.tm_hour = 0;  start_date.tm_min = 0;  start_date.tm_sec = 0;
  start_date.tm_mon = 10; start_date.tm_mday = 15; start_date.tm_year = 113;

  end_date.tm_hour = 0;  end_date.tm_min = 0;  end_date.tm_sec = 0;
  end_date.tm_mon = 10; end_date.tm_mday = 20; end_date.tm_year = 113;

给定 2013 年,mktime 将返回 -1,因为无法表示日历时间。你会认为 3913 年是一个有效的日历时间,原因与2038 年问题有关,正如 Joni 所指出的那样。

于 2013-09-26T18:40:14.503 回答
1

OP did not check mktime()` result.

As @Joni mentions, set the tm_isdst field. Use 0 or 1 if you know if how DST is applied, else use '-1' and let the OS make the determination.

@qchen mentioned the year 1900 offset as you likely want .tm_year = 2013-1900.

I assert the underlying issue is using mktime() without checcking if it is (time_t) -1. With robust code, this return value should be tested and missing that opened OP code to unexpected results.

于 2013-09-26T19:41:01.940 回答
0

除了没有正确指定年份之外,您还tm_isdst没有设置该字段。mktime使用此字段来确定日期是否具有有效的夏令时,或者是否应从时区数据库中查找 DST 设置。这可以使结果减少一小时。添加这些行:

/* lookup if DST or not */
start_date.tm_isdst = -1;
end_date.tm_isdst = -1;
于 2013-09-26T18:56:27.530 回答