C++静态日期类



对于这个问题,我的任务是创建一个;日期";类,该类仅具有一个数据成员,该数据成员持有从"0"开始的天数的整数;基本;日期这是相应的头类

#ifndef _DATE_H_
#define _DATE_H_
#include <QString>
class Date{
public:
const static int BaseYear = 1900; 
Date();
Date(int y, int m, int d);
void set(int y, int m, int d);
QString toString(bool brief);
void setToToday();
QString getWeekDay();
bool lessThan(const Date& d);
bool equals(const Date& d);
int daysBetween(const Date& d);
Date addDate(int Days);
static bool leapYear(int year);
static QString monthName(int month);
static int yearDays(int year);
static int monthDays(int month, int year);
private:
int m_DaysSinceBaseDate;
static int ymd2dsbd(int y, int m, int d);
void getYMD(int& y, int& m, int& d);
};
#endif

当我试图将日期写入字符串时遇到了麻烦,实现声明函数getYMD((应该有助于进行此计算。

如果您已经实现了getYMD方法,您可以使用它的结果来填充struct tm,然后可以使用strftime:将其格式化为字符串

// a class method
QString format() const {
int y, int m, int d;
Date date = *this;
// Passed to strftime(3) 
char buffer[64];
date.getYMD(y, m, d);
struct tm t;
// This saves you from having to zero out
// each field manually
memset(&t, 0, sizeof(struct tm));
t.tm_year = y - 1900; // since 1900
t.tm_mon = m - 1; // zero based
t.tm_day = d;
const char* format = ""; // insert format here
size_t length = strftime(buffer, 64, format, &time_struct);

std::string s(buffer, length);
return QString::FromStdString(s);
}

最新更新