赞
踩
读代码的过程中,遇到2个日期相关的工具函数, 记录一下。
比较日期,计算日期间隔(天数)
- #include<stdio.h>
- #include<Windows.h>
- #include<ctype.h>
- #include<string.h>
-
-
- // 几个日期相关的工具函数
-
- struct Date//日期
- {
- int year;
- int month;
- int day;
- };
-
-
- // 比较两个日期大小
- int compare_date(struct Date start, struct Date end)
- {
- //把日期转化为20180227的形式来比大小
- if (start.year * 10000 + start.month * 100 + start.day <= end.year * 10000 + end.month * 100 + end.day)
- return 1;//正确
- else
- return -1;//错误
- }
-
-
- //计算日期间隔
- int cal_date(struct Date start, struct Date end)
- {
- if (compare_date(start, end) == -1)
- {
- puts("日期错误");
- return -1;
- }
- else
- {
- int y1, m1, d1;
- int y2, m2, d2;
- m1 = (start.month + 9) % 12;
- y1 = start.year - m1 / 10;
- d1 = 365 * y1 + y1 / 4 - y1 / 100 + y1 / 400 + (m1 * 306 + 5) / 10 + (start.day - 1);
- m2 = (end.month + 9) % 12;
- y2 = end.year - m2 / 10;
- d2 = 365 * y2 + y2 / 4 - y2 / 100 + y2 / 400 + (m2 * 306 + 5) / 10 + (end.day - 1);
-
- return (d2 - d1);//日期间隔
- }
- }
-
- int main() {
-
- // 日期函数测试
- struct Date start, end;
-
- start.year = 2024;
- start.month = 7;
- start.day = 15;
-
- end.year = 2024;
- end.month = 8;
- end.day = 1;
-
- printf("start:%d-%d-%d\n", start.year, start.month, start.day);
- printf("end:%d-%d-%d\n", end.year, end.month, end.day);
- printf("compare_date: %d\n", compare_date(start, end));
- printf("cal_date: %d\n", cal_date(start, end));
-
- return 0;
- }
-
- // 输出结果:
- // start:2024-7-15
- // end:2024-8-1
- // compare_date: 1
- // cal_date: 17

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。