自己写了一个计算日期差的函数,不过begin<end,begin>=end的情况没有考虑
#include<stdio.h>
struct date{
unsigned int year;
unsigned short month;
unsigned short day;
};
inline int isleap(unsigned int year)
{
return ((year%4==0&&year%100!=0)||(year%400==0));
}
int diffdate(struct date begin,struct date end)
{
int days;
int months,years;
int tmpyear,tmpmonth,leapyear;
short monthday[2][12]={
{31,28,31,30,31,30,31,30,31,30,31},
{31,29,31,30,31,30,31,30,31,30,31}
};
if(isleap(end.year)){
leapyear =1;
}else{
leapyear = 0;
}
years = end.year - begin.year;
months = end.month - begin.month;
days = end.day - begin.day;
tmpyear = begin.year;
while(years>0){
if(isleap(tmpyear))
days+=366;
else
days+=365;
tmpyear++;
years--;
}
if(months>0){
while(months-->0){
days+=monthday[leapyear][begin.month++-1];
}
}else{
while(months++<0){
begin.month--;
days-=monthday[leapyear][begin.month-1];
}
}
return days;
}
int main(int argc,char** argv)
{
struct date begin,end;
int diff;
if(argc!=7)
return;
begin.year = atoi(argv[1]);
begin.month = atoi(argv[2]);
begin.day = atoi(argv[3]);
end.year = atoi(argv[4]);
end.month = atoi(argv[5]);
end.day = atoi(argv[6]);
diff = diffdate(begin,end);
printf("diff date is:%d/n",diff);
return 0;
}
#include<stdio.h>
struct date{
unsigned int year;
unsigned short month;
unsigned short day;
};
inline int isleap(unsigned int year)
{
return ((year%4==0&&year%100!=0)||(year%400==0));
}
int diffdate(struct date begin,struct date end)
{
int days;
int months,years;
int tmpyear,tmpmonth,leapyear;
short monthday[2][12]={
{31,28,31,30,31,30,31,30,31,30,31},
{31,29,31,30,31,30,31,30,31,30,31}
};
if(isleap(end.year)){
leapyear =1;
}else{
leapyear = 0;
}
years = end.year - begin.year;
months = end.month - begin.month;
days = end.day - begin.day;
tmpyear = begin.year;
while(years>0){
if(isleap(tmpyear))
days+=366;
else
days+=365;
tmpyear++;
years--;
}
if(months>0){
while(months-->0){
days+=monthday[leapyear][begin.month++-1];
}
}else{
while(months++<0){
begin.month--;
days-=monthday[leapyear][begin.month-1];
}
}
return days;
}
int main(int argc,char** argv)
{
struct date begin,end;
int diff;
if(argc!=7)
return;
begin.year = atoi(argv[1]);
begin.month = atoi(argv[2]);
begin.day = atoi(argv[3]);
end.year = atoi(argv[4]);
end.month = atoi(argv[5]);
end.day = atoi(argv[6]);
diff = diffdate(begin,end);
printf("diff date is:%d/n",diff);
return 0;
}