【发布时间】:2023-01-24 00:28:23
【问题描述】:
使用下面的函数,它只是将日期添加到日期 (yyyymmdd),多年来都可以正常工作。
int dateplusdays(int datein, int days) {
int year, month, day;
int dateout;
struct tm date;
time_t secs;
year = (int)floor(datein / 10000.0);
month = (int)floor(datein / 100.0) - year * 100;
day = datein - month * 100 - year * 10000;
date.tm_sec = 0;
date.tm_min = 0;
date.tm_hour = 12;
date.tm_year = year - 1900;
date.tm_mon = month - 1;
date.tm_mday = day;
date.tm_isdst = -1;
secs = mktime(&date) + days * 86400;
date = *localtime(&secs);
dateout = (date.tm_year + 1900) * 10000 + (date.tm_mon + 1) * 100 + date.tm_mday;
return dateout;
}
我使用这个测试代码从 1900 到 2100 进行了压力测试。没有错误!
for (i = 19000101; i < 21001231; i++) {
int a = dateplusdays(i, 0); // make date out of i
if (i == a) { // check for valid date
int b = dateplusdays(a, 1);
int c = dateplusdays(b, 1);
if (b == c)
printf("i:%d a:%d b:%d c:%d\n", i, a, b, c);
}
}
现在...当将 date.tm_hour 从 12 更改为 0 时,我在非常具体的日期正好得到 184 个错误,在 1900-2100 年的范围内完全不规则地分布(例如 30.10.2022 在 30.10 中添加 1 天的结果.2022)。
i:19160930 a:19160930 b:19161001 c:19161001
i:19161001 a:19161001 b:19161001 c:19161001
...
i:20221029 a:20221029 b:20221030 c:20221030
i:20221030 a:20221030 b:20221030 c:20221030
...
i:20381030 a:20381030 b:20381031 c:20381031
i:20381031 a:20381031 b:20381031 c:20381031
最重要的是,仅涉及 9 月至 12 月。
geohei@vm92:~/Devel$ ./dateplusdays | cut -c7-8 | sort | uniq -c
47 09
131 10
6 11
我错过了什么?
【问题讨论】: