我正在寻找一种方法来找出两个日期之间的差异。解决方案需要考虑闰年。请参阅下面的两个代码块。 2012年是闰年,而2013年则没有,因此我无法理解为什么两个项目都会输出“32天的差异”。当time.h确实考虑到闰年时,它们应该是不同的吗?
第一个:
#include <stdio.h>
#include <time.h>
int main ()
{
struct tm start_date;
struct tm end_date;
time_t start_time, end_time;
double days;
start_date.tm_hour = 0; start_date.tm_min = 0; start_date.tm_sec = 0;
start_date.tm_mon = 2; start_date.tm_mday = 1; start_date.tm_year = 112;
end_date.tm_hour = 0; end_date.tm_min = 0; end_date.tm_sec = 0;
end_date.tm_mon = 3; end_date.tm_mday = 1; end_date.tm_year = 112;
start_time = mktime(&start_date);
end_time = mktime(&end_date);
days = difftime(end_time, start_time) / 86400;
printf ("%.f days difference\n", days);
return 0;
}
第二个:
#include <stdio.h>
#include <time.h>
int main ()
{
struct tm start_date;
struct tm end_date;
time_t start_time, end_time;
double days;
start_date.tm_hour = 0; start_date.tm_min = 0; start_date.tm_sec = 0;
start_date.tm_mon = 2; start_date.tm_mday = 1; start_date.tm_year = 113;
end_date.tm_hour = 0; end_date.tm_min = 0; end_date.tm_sec = 0;
end_date.tm_mon = 3; end_date.tm_mday = 1; end_date.tm_year = 113;
start_time = mktime(&start_date);
end_time = mktime(&end_date);
days = difftime(end_time, start_time) / 86400;
printf ("%.f days difference\n", days);
return 0;
}
答案 0 :(得分:6)
Buddy只需尝试以下操作(将您的月份分别更改为1和2而不是2和3,它将为您提供正确的结果,此更改已经过测试)。
按照约阿希姆和弗洛里斯的说法, 对于tm_mon成员,月份为零,您计算的是3月1日到4月1日之间的差异,而不是2月1日和3月1日。
start_date.tm_hour = 0; start_date.tm_min = 0; start_date.tm_sec = 0;
start_date.tm_mon = 1; start_date.tm_mday = 1; start_date.tm_year = 112;
end_date.tm_hour = 0; end_date.tm_min = 0; end_date.tm_sec = 0;
end_date.tm_mon = 2; end_date.tm_mday = 1; end_date.tm_year = 112;