这里有一个类,请增加类成员函数,判断两个日期差距多少天,函数传参类型是int,日期格式是YYYYMMDD ``` class CDateTime { private: int us; int ms; time_t now; struct tm dateTime; struct timeval tval; public: CDateTime() { Initialize(); } CDateTime(int YYYYMMDD) { std::string timestr = std::to_string(YYYYMMDD); try { std::cout << "::" << timestr.length() << std::endl; int year = std::stoi(timestr.substr(0, 4)); std::cout << "::" << timestr.substr(0, 4) << std::endl; int month = std::stoi(timestr.substr(4, 2)); std::cout << "::" << timestr.substr(4, 2) << std::endl; int day = std::stoi(timestr.substr(6, 2)); std::cout << "::" << timestr.substr(6, 2) << std::endl; dateTime.tm_year = year - 1900; dateTime.tm_mon = month - 1; dateTime.tm_mday = day; dateTime.tm_hour = 0; dateTime.tm_min = 0; dateTime.tm_sec = 0; } catch (std::out_of_range &e) { Initialize(); } } CDateTime(int year, int month, int day, int hour, int minute, int second) { dateTime.tm_year = year - 1900; dateTime.tm_mon = month - 1; dateTime.tm_mday = day; dateTime.tm_hour = hour; dateTime.tm_min = minute; dateTime.tm_sec = second; } void Initialize() { gettimeofday(&tval, NULL); now = (time_t)tval.tv_sec; ms = (int)tval.tv_usec / 1000; us = (int)tval.tv_usec; #ifdef _WIN32 localtime_s(&dateTime, &now); #else localtime_r(&now, &dateTime); #endif } ```
时间: 2024-02-14 15:04:59 浏览: 96
Sql Server 中利用Convert 函数转换日期格式
可以增加一个成员函数,计算两个日期对象之间相差的天数,代码如下:
```
int GetDateDiff(CDateTime& dt)
{
// 转换当前日期和参数日期为time_t类型
time_t t1 = mktime(&dateTime);
time_t t2 = mktime(&dt.dateTime);
// 计算相差秒数并转换为天数
int diff = (int)difftime(t2, t1);
int days = diff / (3600 * 24);
return days;
}
```
在这个函数中,我们使用`mktime`函数将日期对象转换为`time_t`类型的时间戳,然后计算两个时间戳之间相差的秒数,并将其转换为天数返回。
阅读全文