#include<iostream> using namespace std; class CDate; istream& operator>> (istream &input, CDate &c1); ostream& operator<< (ostream &output, const CDate &c1); class CDate { public: CDate(); CDate(int year,int month,int day); ~CDate(); CDate operator + (long day); CDate operator - (long day); long operator - (CDate &rhs); int isLeapYear (int year); void WeekDay(); friend ostream &operator << (ostream &,const CDate &); friend istream &operator >> (istream &,CDate &); private: int m_year,m_month,m_day; long date2int(CDate); CDate int2date(int); }; int days[12] = {31,28,31,30,31,30,31,30,31,31,30,31}; // 1 2 3 4 5 6 7 8 9 10 11 12 CDate::CDate() { } CDate::CDate(int year, int month, int day) { this->m_year = year; this->m_month = month; this->m_day = day; } CDate::~CDate() {} istream& operator>> (istream &input, CDate &c1) { input>>c1.m_year>>c1.m_month>>c1.m_day; return input; } ostream& operator<< (ostream &output, const CDate &c1) { output<<c1.m_year<<"/"<<c1.m_month<<"/"<<c1.m_day; return output; } long CDate::date2int(CDate a) { long ret = a.m_year*365 + (a.m_year-1)/4 - (a.m_year -1)/100 + (a.m_year -1)/400; days[1]+=isLeapYear(a.m_year); for(int i=0; i<a.m_month-1; ret+=days[i++]); days[1] = 28; return ret+this->m_day; } CDate CDate::int2date(int a) { CDate ret; ret.m_year = a/146097*400; for(a%=146097;a>=365+isLeapYear(ret.m_year); a-=365+isLeapYear(ret.m_year),ret.m_year++); days[1] +=isLeapYear(ret.m_year); for(ret.m_month=1; a>=days[ret.m_month-1]; a-=days[ret.m_month-1], ret.m_month++); days[1] = 28; ret.m_day = a+1; return ret; } CDate CDate::operator+(long days) { return int2date(date2int(*this)+days); } CDate CDate::operator-(long days) { return int2date(date2int(*this)-days); } long CDate::operator- (CDate& rhs) { return date2int(*this) - date2int(rhs); } int CDate::isLeapYear(int year) { return (0==year%4 && 0!=year%100) || 0==year%400; } void CDate::WeekDay() { int tm = this->m_month>=3 ? (this->m_month-2):(this->m_month+10); int ty = this->m_month>=3 ? this->m_year:(this->m_year-1); int num = (ty + ty/4 - ty/100 + ty/400 + (int)(2.6*tm - 0.2)+this->m_day)%7; cout<<"星期:"; switch (num) { case 1: cout<<"Monday"<<endl;break; case 2: cout<<"Tuseday"<<endl; break; case 3: cout<<"Wednesday"<<endl;break; case 4: cout<<"Thursday"<<endl;break; case 5: cout<<"Friday"<<endl;break; case 6: cout<<"Saturday"<<endl;break; case 7: cout<<"Sunday"<<endl;break; } } int main() { CDate c1,c2,c3, c4; cout<<"请输入某一天的日期:"<<endl; cin>>c1; cout<<"输入的是:"<<c1<<endl; c1.WeekDay(); long t; cout<<"Input t:"<<endl; cin>>t; c2 = c1+t; cout<<t<<"天后:"<<c2<<endl; c2.WeekDay(); c3=c1-t; cout<<t<<"天前:"<<c3<<endl; c3.WeekDay(); cout<<"请输入另一天的年月日"<<endl; cin>>c4; cout<<"输入的是:"<<c4<<endl; c4.WeekDay(); t=c1-c4; cout<<"相差:"<<t<<"天"<<endl; return 1; }
CDate.cpp
最新推荐文章于 2022-10-24 22:33:45 发布