我想编写一个自定义类DateAndTime,以简化项目中与日期有关的工作。问题是我不能正确地比较日期或者我有一个转换日期的问题。
我的目标是:
请帮帮我:)
这是我的密码
#include <iostream>
#include <sstream>
#include <ctime>
using namespace std;
class DateAndTime
{
private:
const std::string dateTemplate = "%Y-%m-%d %H:%M";
public:
int year;
int month;
int day;
time_t fullDate;
public:
DateAndTime(std::string dataString)
{
struct tm tm;
strptime(dataString.c_str(), dateTemplate.c_str() ,&tm);
year = 1900 + tm.tm_year;
month = 1 + tm.tm_mon;
day = tm.tm_mday;
fullDate = mktime(&tm);
cout << "Date from string: " << ctime(&fullDate) << endl;
}
DateAndTime()
{
time_t currentDate;
struct tm * localDate;
time (¤tDate);
localDate = localtime (¤tDate);
fullDate = currentDate;
year = 1900 + localDate->tm_year;
month = 1+ localDate->tm_mon;
day = localDate->tm_mday;
cout << "Current date: " << ctime(&fullDate) << endl;
}
public:
std::string toString()
{
return std::to_string(year) + "-" + std::to_string(month) + "-" + std::to_string(day);
}
int diffDays(DateAndTime data)
{
return difftime(data.fullDate, this->fullDate) / 86400;//devide by 1d in seconds
}
};
int main()
{
//Now
DateAndTime d1;
cout<< d1.year << endl;
cout<< d1.month << endl;
cout<< d1.day << endl;
cout << d1.toString() << endl << endl;
//Other
string d = "2021-14-01 14:17:33";
DateAndTime d2(d);
cout<< d2.year << endl;
cout<< d2.month << endl;
cout<< d2.day << endl;
cout<< d2.toString();
cout << endl;
cout << "Diff days: " << d1.diffDays(d2);
return 0;
}
结果:
Current date: Thu Jan 14 14:40:18 2021
2021
1
14
2021-1-14
Date from string: Wed Mar 28 07:53:20 -26461971
2021
-314878271
32767
2021--314878271-32767
Diff days: -2147483648*
您的模板(CODEY-M-D H:M/CODE>)与您的输入(CODE2021-14-01 14:17:33/CODE>)不匹配,您没有检查错误。
最好在C中完全初始化
在Op's的情况下,