我的思路是先计算两整年相隔多少天,再减去日期小的那个日期那年已经过去的天数,最后加上日期大的那个日期那年已经过去的天数。
/* 标准文档模板 */
#include "stdio.h"
int IsLeap(int year)//判断闰年。能被4整除且又能不能被100整除 是闰年,能直接被400整除也是闰年
{
if(year%4==0&&year%100!=0||year%400==0)
return 1;
else return 0;
}
int PastedDaysOfThisYear(int y,int m,int d)//计算给出的年月日距离当年已经过了多少天
{
int i,temp=d;
for(i = 1;i < m; i++)
{
if(IsLeap(y)==0)//平年
{
switch (i)
{
case 1:case 3:case 5:case 7:case 8:case 10:case 12: temp += 31;break;
case 2:temp += 28;break;
case 4:case 6:case 9 :case 11: temp += 30;break;
}
}
else//闰年
{
switch (i)
{
case 1:case 3:case 5:case 7:case 8:case 10:case 12: temp += 31;break;
case 2:temp += 29;break;
case 4:case 6:case 9 :case 11: temp += 30;break;
}
}
}
return temp;
}
int PastedDaysBeforeThisYear(int yE,int yS)//计算任给的两年相差多少天
{ int res = 0,i=1;
if(yE - yS == 0)
return res;
else
{
while(yS+i <= yE)
{
if(IsLeap(yS+i-1)) res += 366;
else res+=365;
i++;
}
}
return res;
}
int days(long long e,long long s)//计算任给两个日期之间的相隔天数
{
int y[2],m[2],d[2],sum;
y[0] = e/10000;
y[1] = s/10000;
m[0] = e%10000/100;
m[1] = s%10000/100;
d[0] = e%10000%100;
d[1] = s%10000%100;
sum = PastedDaysBeforeThisYear(y[0],y[1])-PastedDaysOfThisYear(y[1],m[1],d[1])+PastedDaysOfThisYear(y[0],m[0],d[0]);
return sum;
}
void main()
{
printf("%d", days(20131021,19981019));
getch();
}