当前位置:网站首页>C语言计算日期间隔天数
C语言计算日期间隔天数
2022-07-26 10:29:00 【Neo Wordsworth】
要计算两个日期相关多少天,
网上看到一个“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;
}边栏推荐
- Agenda express | list of sub forum agenda on July 27
- Use of Android grendao database
- INSTALL_ FAILED_ SHARED_ USER_ Incompatible error resolution
- mysql 进不去了怎么办
- [Halcon vision] polar coordinate transformation
- 【Halcon视觉】形态学腐蚀
- RecyclerView最后一条显示不全或显示部分的问题解决
- What is wrong about the description of function templates (how to solve link format errors)
- modelsim 安装教程(应用未安装)
- 我们的Web3创业项目,黄了
猜你喜欢
随机推荐
On the compilation of student management system of C language course (simple version)
[Halcon vision] image gray change
[C language] named type and anonymous type
函数模板参数(函数参数在哪)
Learning about opencv (2)
Learning about tensorflow (I)
Application of crosstab in SQL Server
equals与==的区别
Network related journals and conferences in CS
modelsim 安装教程(应用未安装)
Replay the snake game with C language (II) end
Mlx90640 infrared thermal imager temperature sensor module development notes (6)
软件打不开了
Under win10 64 bit, matlab fails to configure notebook
[Halcon vision] programming logic
Interview questions and answers of the first company (I)
Learning about tensor (III)
Li Kou daily question 917
Agenda express | list of sub forum agenda on July 27
【socket】三次握手是在listen中完成,accept只从完成连接的队列中拿出一个连接







![[Halcon vision] morphological corrosion](/img/f9/f01dd3340824ff28c84cf7bb52882e.png)

![[Halcon vision] image gray change](/img/62/426713becba851f034e6008f28bdb0.png)