2024年2月21日发(作者:)
throw "minute is invalid"; else throw "second is invalid";}Time::Time(){ time_t now; time(&now); struct tm *t_now; t_now = localtime(&now); hour = t_now->tm_hour; minute = t_now->tm_min; second = t_now->tm_sec;}int Time::getSec() const{ return second;}int Time::getMin() const{ return minute;}int Time::getHour() const{ return hour;}bool Time::setSec(int sec){ if (sec >= 0 && sec <= 60) { second = sec; return true; } else return false;}bool Time::setMin(int minute_){ if (minute_ >= 0 && minute_ <= 60) { minute = minute_; return true; } else return false;}bool Time::setHour(int hour_){ if (hour_ >= 0 && hour_ <= 12) { hour = hour_; return true; } else return false;}string Time::toString(){ return to_string(hour) + ":" + to_string(minute) + ":" + to_string(second);}date.h#pragma once#include #include "time.h"using std::string;class Date{public: Date(int, int, int); Date(); void addDay(int); string toString(char); static Date *getInstance(); bool setYear(int year_); int getYear() const; bool setMon(int month_); int getMon() const; bool setDay(int day_); int getDay() const; Time getTime() const;private: int year; int month; int day; static const int maxDay[2][13]; static Date *mpDate; Time time;};
#pragma once#include #include #include #include "date.h"using std::cout;using std::endl;const int Date::maxDay[2][13] = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};Date::Date(int year_, int month_ = 1, int day_ = 1){ if (year_ >= 1900 && year_ <= 9999) if (month_ >= 1 && month_ <= 12) if (day_ >= 1 && day_ <= maxDay[(year_ % 4 == 0 && year_ % 100 != 0) || year_ % 400 == 0][month_]) { year = year_; month = month_; day = day_; } else throw "day is invalid"; else throw "month is invalid!"; else throw "year is invalid!";}Date::Date(){ time_t now; std::time(&now); struct tm *t_now; t_now = localtime(&now); year = t_now->tm_year + 1900; month = t_now->tm_mon + 1; day = t_now->tm_mday;}void Date::addDay(int n){ day += n; if (day > maxDay[(year % 4 == 0 && year % 100 != 0) || year % 400 == 0][month]) { day %= maxDay[(year % 4 == 0 && year % 100 != 0) || year % 400 == 0][month]; month++; if (month > 12) { year++; month %= 12; } }}string Date::toString(char spor){ return std::to_string(year) + spor + std::to_string(month) + spor + std::to_string(day);}bool Date::setYear(int year_){ if (year_ >= 1900 && year_ <= 2120) { year = year_; return true; } else return false;}int Date::getYear() const{ return year;}bool Date::setMon(int month_){ if (month_ >= 1 && month_ <= 12) { month = month_; return true; } else return false;}int Date::getMon() const{ return month;}bool Date::setDay(int day_){ if (day_ >= 1 && day_ <= maxDay[(year % 4 == 0 && year % 100 != 0) || year % 400 == 0][month]) { day = day_; return true; } else return false;}int Date::getDay() const{ return day;
}Time Date::getTime() const{ return time;}
发布评论