c++ - 两个日期之间有多少天 C++

标签 c++ date date-arithmetic

我有一个程序使用我在一个类中定义的两个函数。我的类(class)工作正常,但我的程序总是返回一定数量的假期。当日期相距较远时,会出现更多错误。我的代码旨在在一个函数中计算自 1582 年以来的总天数,另一个函数从较小的天数中减去较高的天数。我从哪里得到错误?我知道这可能不是最有效的做事方式(cpu 明智的)但是有人能找到我的逻辑在哪里搞砸了吗?这也说明了闰年。我一直在根据网站检查我的程序 http://www.timeanddate.com/date/durationresult.html

int Date::totalDays()
{
    int totalDays = 0;
    int daysInMonth[]={0,31,28,31,30,31,30,31,31,31,31,30,31};
    totalDays += day;
    for (int i = month-1; i > 0; i--)
    {
        totalDays += daysInMonth[i];
    }
    for (int i = year-1; i > 1582; i--)
    {
        if(year % 100 == 0)
        {
            if(year % 400 == 0)
                totalDays += 366;
            else
                totalDays += 365;
        }
        else
        {
            if(year % 4 == 0)
                totalDays += 366;
            else
                totalDays += 365;
        }
    }
    return totalDays;
}

int Date::daysBetween(Date other)
{
    if (this->totalDays() > other.totalDays())
        return this->totalDays() - other.totalDays();
    else
        return other.totalDays() - this->totalDays();
}

谢谢。

最佳答案

问题一:

int daysInMonth[]={0,31,28,31,30,31,30,31,31,31,31,30,31};

应该是

int daysInMonth[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
//                                           ^^

问题2:

如果当前 year 是闰年,并且 month 大于 2,您还需要添加一天来计算 2 月 29 日当前年份。

关于c++ - 两个日期之间有多少天 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36045961/

相关文章:

c++ - 如何将 "iterate"设置为 0x104567910

mysql - 如何结合 Date_format 和 Date_sub

JavaScript 日期时间格式

C++/将时间(NULL)转换为从 1970 年 1 月 1 日起的精确年、月、周、小时和分钟

c++ - 使用运行时类型开关(和模板化函数)避免代码重复

c++ - 调试为什么 size_t 不能作为数据成员工作?

c++ - 如何调用另一个类的静态方法

sql - 如何从一个日期获取下一个记录日期和从一个日期获取最后一个记录日期?

javascript - Jscript 在开发和测试机器上返回不同的(计算的)结果 - 使用相同的代码

php - 计算夜间月光时间的算法