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

问题描述

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

我的目标是找出1900-01-01与给定日期之间的天数。日期的格式为 as 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-29and 2019-02-01。在这两种情况下,输出都是43494。整个2月,产出比预期少3天。然后,到了 2019 年 3 月,产量又恢复正常。另一种情况是2019-09-03,输出为43710,而预期输出为43711

为什么这些特定日期会发生这种情况?我一步一步地运行解决方案,仔细观察内存中的变量,但无法解释。

任何建议表示赞赏。谢谢。

标签: c++timedate-difference

解决方案


月份应表示为 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一定返回秒数(您假设)。


推荐阅读