提问者:小点点

C++中转换和比较日期的问题


我想编写一个自定义类DateAndTime,以简化项目中与日期有关的工作。问题是我不能正确地比较日期或者我有一个转换日期的问题。

我的目标是:

  1. 将DateAndTime创建为当前日期/li>

请帮帮我:)

这是我的密码

#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 (&currentDate);
             localDate = localtime (&currentDate);
             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*

共2个答案

匿名用户

您的模板(CODEY-M-D H:M/CODE>)与您的输入(CODE2021-14-01 14:17:33/CODE>)不匹配,您没有检查错误。

匿名用户

最好在C中完全初始化,它的不设置使用的的每个成员。

在Op's的情况下,:(可能是其他)没有被分配或预先初始化,可能导致错误的结果。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中|转换|日期)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?