简体   繁体   English

time.h是否允许Le年C

[英]Does time.h Allow Leap Years C

I am looking for a way to find the difference between two dates. 我正在寻找一种找到两个日期之间差异的方法。 The solution needs to take into account leap years. 该解决方案需要考虑leap年。 Please see the two blocks of code below. 请参见下面的两个代码块。 2012 was a leap year whereas 2013 was not, and so I fail to understand why both programs output "32 days difference". 2012年是a年,而2013年不是a年,因此我不明白为什么两个程序都输出“ 32天差异”。 Surely they should be different if time.h does indeed take into account leap years? 如果time.h确实考虑到leap年,那么他们当然应该有所不同吗?

The first: 首先:

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

The second: 第二:

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

Buddy just try the following (change your month as 1 and 2 respectively instead of 2 and 3, it will give you correct results, this change is tested). 好友只需尝试以下操作(将您的月份分别更改为1和2而不是2和3,它将为您提供正确的结果,此更改已通过测试)。

As per Joachim and Floris, Month is zero based for tm_mon member, and you were counting the difference between March 1 and April 1 instead of Feb 1 and Mar 1. 根据Joachim和Floris,对于tm_mon成员,Month为零,您正在计算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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM