要计算两个日期相关多少天,
网上看到一个“C语言计算日期间隔天数的经典算法解析”文章,其代码如下:
int day_diff(int year_start, int month_start, int day_start, int year_end, int month_end, int day_end){int y2, m2, d2;int y1, m1, d1;m1 = (month_start + 9) % 12;y1 = year_start - m1/10;d1 = 365*y1 + y1/4 - y1/100 + y1/400 + (m1*306 + 5)/10 + (day_start - 1);m2 = (month_end + 9) % 12;y2 = year_end - m2/10;d2 = 365*y2 + y2/4 - y2/100 + y2/400 + (m2*306 + 5)/10 + (day_end - 1);return (d2 - d1);}
我用java随机生成一些数据去验证这个c代码,有些数据不对,比如
4645-8-25
5074-4-28
java计算如下:
(int) ((c2.getTime().getTime() - c1.getTime().getTime()) / (1000 * 3600 * 24));
然后自己写了个代码,
u8 IsLeapYear(u16 year){if ((year & 0x03) == 0) {if ((year >> 2) % 25 == 0) {if ((year & 0x0f) == 0)return 1;} else {return 1;}}return 0;}const u8 offset[]= {0,0,1,5,6,8,9,11,12,13,15,16,18};u32 CalDayDiff(MyDate* s,MyDate* e){u32 yDiff,i;u32 sum=0,sum2;MyDate d;yDiff=e->year-s->year;if(yDiff>1){for(i=s->year+1;i<e->year;i++){sum+=IsLeapYear(i)?366:365;}yDiff=1;}switch(yDiff){case 0:sum=((e->month-1)<<5)-offset[e->month]+e->day;if(e->month>2 && IsLeapYear(e->year))sum+=1;sum2=((s->month-1)<<5)-offset[s->month]+s->day;if(s->month>2 && IsLeapYear(s->year))sum2+=1;sum-=sum2;break;case 1:d.year=s->year;d.month=12;d.day=31;sum+=CalDayDiff(s,&d);d.year=e->year;d.month=1;d.day=1;sum+=CalDayDiff(&d,e)+1;break;}return sum;}