#include <stdio.h> #include <math.h> typedef struct { int year,month,day; }Date; int yearday(int year) { int yday; if(year%4==0&&year%100!=0||year%400==0) yday=366; else yday=365; return yday; } int monthday(int year) { int mday; if(year%4==0&&year%100!=0||year%400==0) mday=29; else mday=28; return mday; } int dayofyear(Date d) { int i,total=0; int months[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; months[2]=monthday(d.year); for(i=1;i<d.month;i++) total=total+months[i]; total=total+d.day; return total; } int cmpdate(Date d,Date s) { int result; if(d.year==s.year) { if(d.month==s.month) { if(d.day==s.day) result=0; else result=d.day-s.day; } else result=d.month-s.month; } else result=d.year-s.year; return result; } int interday(Date d,Date s) { int result,te,ts,total; int year,start,end,day; int i; result=cmpdate(d,s); if(result>0) { start=s.year; end=d.year; te=dayofyear(d); ts=dayofyear(s); } else if(result<0) { start=d.year; end=s.year; ts=dayofyear(d); te=dayofyear(s); } else return 0; if(start==end) return abs(te-ts); else { total=0; for(i=start;i<=end;i++) { day=yearday(i); if(i==start) total=total+day-ts; else if(i==end) total=total+te; else total=total+day; } } return total; } int main() { Date d1,d2; int y,n; printf("input date:"); scanf("%d%d%d",&d1.year,&d1.month,&d1.day); scanf("%d%d%d",&d2.year,&d2.month,&d2.day); y=yearday(d1.year); n=dayofyear(d1); printf("%d days %dn",d1.year,y); printf("%d-%d-%d is the %d day.n",d1.year,d1.month,d1.day,n); n=interday(d1,d2); printf("%d-%d-%d and %d-%d-%d distance ",d1.year,d1.month,d1.day,d2.year,d2.month,d2.day); printf("%d daysn",n); return 0; }
input date:2009 2 1 2015 2 1
2009 days 365
2009-2-1 is the 32 day.
2009-2-1 and 2015-2-1 distance 2191 days