我试图通过使用下面的 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 之间的年份,为什么我会得到正确的输出。