#include<iostream>
using namespace std;
class Date
{
public:
Date(int year,int month,int day)
:_year(year)
,_month(month)
,_day(day)
{
if(year<1900||month<1||month>12||day<1||day>GetMonthDay(year,month))
cout<<"Invalid Date"<<endl;
}
bool IsLeapYear(int year)//判断是否是闰年
{
return (year%4==0&&year%100!=0||year%400==0);
}
int GetMonthDay(int year,int month)//获取每个月的天数
{
int MonthArr[12]={31,28,31,30,31,30,31,31,30,31,30,31};
if(IsLeapYear(year)&&month==2)
{
return MonthArr[month-1]+1;
}
else
return MonthArr[month-1];
}
Date operator+(int day)//日期+天数
{
Date tmp(*this);
tmp._day +=day;
while(tmp._day >GetMonthDay(tmp._year ,tmp._month ))
{
tmp._day -=GetMonthDay(tmp._year ,tmp._month );
if(tmp._month ==12)
{
tmp._year +=1;
tmp._month =1;
}
else
{
tmp._month +=1;
}
}
return tmp;
}
Date operator-(int day)//日期-天数
{
Date tmp(*this);
tmp._day -=day;
while(tmp._day <0)
{
tmp._day =GetMonthDay(tmp._year ,tmp._month )-(-tmp._day) ;
if(tmp._month ==1)
{
tmp._year -=1;
tmp._month =12;
}
else
{
tmp._month -=1;
}
}
return tmp;
}
int operator-(const Date& d)//日期减日期
{
int countday=0;
int countmonth=0;
int countyear=0;
Date tmp(*this);
if(_day<d._day )
{
countday=_day+GetMonthDay(d._year,d._month)-d._day ;
_month=_month-1;
}
else
{
countday=_day-d._day ;
}
if(_month<d._month )
{
while(_month)
{
countmonth+=GetMonthDay(_year,_month);
_month--;
}
int n=12-d._month;
while(n)
{
Date tmp(*this);
countmonth+=GetMonthDay(d._year ,d._month+n-1 );
n -- ;
}
_year=_year-1;
}
else
{
int n=_month-d._month;
while(n)
{
countmonth+=GetMonthDay(d._year ,d._month+n-1 );
n--;
}
}
if(IsLeapYear(d._year))
{
countyear=(_year-d._year )*366;
}
else
{
countyear=(_year-d._year )*365;
}
return countday+countmonth+countyear;
}
void Display()
{
cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
}
private:
int _year;
int _month;
int _day;
};
void Test1()
{
Date d1(2015,1,16);
d1.Display ();
//(d1+34).Display ();
(d1-30).Display ();
}
void Test2()
{
Date d1(2015,11,13);
d1.Display ();
Date d2(2015,10,13);
d2.Display ();
cout<<d1-d2<<endl;//日期-日期
}
int main()
{
Test2();
system("pause");
return 0;
}原文:http://760470897.blog.51cto.com/10696844/1753215