我在想办法找出两次约会的区别。解决方案需要考虑闰年。请看下面两段代码。2012年是闰年,而2013年不是,所以我不明白为什么这两个项目都输出“32天差异”。如果时间真的考虑到闰年,它们肯定会有所不同?
第一个:

#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;
}

最佳答案

巴迪试试下面的方法(把你的月份分别改为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;

关于c - time.h是否允许Le年C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24405822/

10-11 18:31