解决方案在两个日期之间的天数内不起作用

Solution doesn't work for number of days between two dates

本文关键字:之间 不起作用 日期 两个 解决方案      更新时间:2023-10-16

我知道这个问题已经被问了几次,我再问一次是因为我对 SO 的现有解决方案有问题。

我的目标是找到1900-01-01和给定日期之间的天数。日期的格式为yyyy-mm-dd,类型为std::string

我遵循的解决方案是 https://stackoverflow.com/a/14219008/2633803

以下是我的版本:

std::string numberOfDaysSince1900v2(std::string aDate)
{
string year, month, day;
year = aDate.substr(0, 4);
month = aDate.substr(5, 2);
day = aDate.substr(8, 2);
struct std::tm a = { 0,0,0,1,1,100 }; /* Jan 1, 2000 */
struct std::tm b = { 0,0,0,std::stoi(day),std::stoi(month),std::stoi(year) - 1900 };
std::time_t x = std::mktime(&a);
std::time_t y = std::mktime(&b);
double difference;
if (x != (std::time_t)(-1) && y != (std::time_t)(-1))
{
difference = std::difftime(y, x) / (60 * 60 * 24) + 36526; //36526 is number of days between 1900-01-01 and 2000-01-01
}
return std::to_string(difference);
}

它工作正常,直到给定的日期到2019-01-292019-02-01。在这两种情况下,输出都是43494。整个 2 月,产量比预期少 3 天。然后,到了2019年3月,产量又恢复正常了。 另一种情况是2019-09-03,输出是43710,而期望的输出是43711

为什么这些特定日期会发生这种情况?我一步一步地运行解决方案,并密切关注内存中的变量,但无法解释它。

任何建议不胜感激。谢谢。

月份应表示为 0 到 11 之间的整数,而不是 1 到 12。

所以

struct std::tm a = { 0,0,0,1,0,100 }; /* Jan 1, 2000 */
struct std::tm b = { 0,0,0,std::stoi(day),std::stoi(month)-1,std::stoi(year) - 1900 };

我会说你的代码还有其他问题。您无法可靠地初始化这样的tm(不保证结构中字段的顺序(。difftime也不一定返回秒数(您假设(。