第一种方法:算出两个日期与公元0年0月0日的日期差,再进行相减(容易理解)
#include <stdio.h>
int sum(int y,int m,int d)
{
unsigned char x[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int i,s=0;
for(i=1;i<y;i++)
if(i%4==0 && i%100!=0 || i%400==0)
s+=366;//闰年
else
s+=365;//平年
if(y%4==0 && y%100!=0 || y%400==0)
x[2]=29;
for(i=1;i<m;i++)
s+=x[i];//整月的天数
s+=d;//日的天数
return s;//返回总天数,相对公元1年
}
int main()
{
unsigned int y1,m1,d1,y2,m2,d2;
long int s1,s2;
printf("输入第一个年 月 日:");
scanf("%d %d %d",&y1,&m1,&d1);
printf("输入第二个年 月 日:");
scanf("%d %d %d",&y2,&m2,&d2);
s1=sum(y1,m1,d1);
s2=sum(y2,m2,d2);
if (s1 > s2)
printf("相差天数:%ld\n",s1-s2);
else
printf("相差天数:%ld\n",s2-s1);
}
第二种方法:直接对两个日期进行计算,不是很容易理解
#
#include<stdio.h>
//判断闰年,如果是闰年返回1,否则返回0
int isYear(int year)
{
return (year%4==0)&&( year %400==0 || year %100!= 0) ? 1:0;
}
//返回该年 year 该月 month 的最大天数
int getDayOfMonth(int year , int month)
{
int dayArr[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
return (month == 2 && isYear(year)==1) ? dayArr[month]+1 : dayArr[month] ;
}
//获取两个日期之间的天数,第一个日期必须比第二个日期小 :)
long int getTotalDay(int year1,int month1,int day1,int year2,int month2,int day2)
{
long total = 0;
for(int year = year1; year < year2 ; year ++ )
{
total = total + 365;
if(isYear(year)==1)
total ++;
}
for(int month =1; month < month2; month ++ )
{
total = total + getDayOfMonth(year2,month);
}
total = total + day2;
for(int month=1 ; month < month1; month ++ )
{
total = total - getDayOfMonth(year1,month);
}
return total - day1;
}
int main()
{
int year1 ,month1,day1;
int year2, month2,day2;
do{//控制日期输进合法,同时year1应该小于year2
printf("\nInput year1-month1-day1\n(such as 2012-12-12) : ");
scanf("%d-%d-%d", &year1,&month1,&day1);
} while( year1 <0 || month1<1 || month1>12 || day1<1|| day1> getDayOfMonth(year1,month1));
do{//控制日期输进合法
printf("\n\n\nInput year2-month2-day2\n(such as 2014-12-12) : ");
scanf("%d-%d-%d", &year2,&month2,&day2);
} while( year2 <0 || year2 <year1|| month2<1 || month2>12 || day2<1|| day2> getDayOfMonth(year2,month2));
printf("\nBetween two date have: %ld days \n\n\n", getTotalDay(year1,month1,day1,year2,month2,day2));
return 0;
}