【问题标题】:Solution doesn't work for number of days between two dates解决方案在两个日期之间的天数内不起作用
【发布时间】:2019-12-17 02:12:48
【问题描述】:

我知道这个问题已经被问过几次了,我再次问是因为我对 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

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

感谢任何建议。谢谢。

【问题讨论】:

  • 您遵循的解决方案使用 5 表示 6 月,使用 6 表示 7 月。你认为这是一个错误吗?

标签: c++ time date-difference


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多