You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++不使用日期时间库计算日期差:新冠自评估工具开发问题

问题解决:日期与2021年1月1日的天数差计算

你需要完成两个核心步骤来实现需求:创建基准日期对象,确保Date类支持合法的减法操作。

实现步骤

  • 创建2021年1月1日的Date对象:根据你的Date类构造函数的参数格式,实例化一个代表2021-01-01的对象,比如Date baseline(1, 1, 2021);(具体参数顺序要匹配Date类的构造定义,比如有的是年、月、日,需要对应调整)。
  • 确保Date类的减法运算符重载支持const对象:你的Date类必须重载operator-,并且这个运算符要能处理const引用的Date对象。如果是成员函数形式,需要声明为const成员,比如:
    class Date {
    public:
        // 其他成员
        int operator-(const Date& other) const;
    };
    
    这个函数的作用是返回当前Date对象与other对象之间的天数差(比如当前日期晚于基准日期则返回正数,反之负数)。

修改后的完整代码

//Include proper libraries
#include <iostream>
#include <cstdlib>

using namespace std;

//Include header files
#include "Date.h"
#include "CalcDays.h"

//Define function to calculate the amount of time between exposure and users second shot
int calcDays(const Date& constRefDate1, const Date& constRefDate2) {

    //Define local var
    int daysDiff1;
    int daysDiff2;

    // 创建2021年1月1日的基准日期对象,参数顺序需匹配Date类构造函数
    Date baselineDate(1, 1, 2021); 

    //Calculate the difference between the input date and 1/1/2021
    daysDiff1 = constRefDate1 - baselineDate;
    daysDiff2 = constRefDate2 - baselineDate;

    //Return the difference between date exposed and date you have gotten the shot
    return abs(daysDiff1 - daysDiff2);
}

关键说明

  • 如果你的Date类构造函数参数顺序是年、月、日,则需要把baselineDate的创建改成Date baselineDate(2021, 1, 1);,务必和Date类的定义一致。
  • 重载的operator-需要正确计算两个日期之间的天数差,要处理闰年、不同月份的天数差异等边界情况,确保计算结果准确。

内容的提问来源于stack exchange,提问作者Justin s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 20:35:26