#include"DateClass.h"
int Date::GetMonthDay(int year, int month)
{
static int daysArr[13] = { 0,31,28,31,30,31,30,31,31,30,31,30, 31 };
if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0))
{
return 29;
}
else
return daysArr[month];
}
Date::Date(int year, int month, int day)
{
if (month > 0 && month < 13 && day < GetMonthDay(year, month))
{
_year = year;
_month = month;
_day = day;
}
else
{
cout << "非法日期" << endl;
assert(false);
}
}
bool Date::operator>(const Date& d)const
{
if (_year > d._year)
{
return true;
}
if (_year == d._year && _month > d._month)
{
return true;
}
if (_year == d._year && _month == d._month && _day > d._day)
{
return true;
}
return false;
}
bool Date::operator==(const Date& d)const
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
bool Date::operator<(const Date& d)const
{
return !(*this > d || *this == d);
}
bool Date::operator>=(const Date& d)const
{
return *this > d || *this == d;
}
bool Date::operator<=(const Date& d)const
{
return !(*this > d);
}
bool Date::operator!=(const Date& d)const
{
return !(*this == d);
}
Date& Date::operator+=(const int day)
{
if (day < 0)
{
return *this -= -day;
}
_day += day;
while(_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
_month++;
if (_month == 13)
{
_year++;
_month = 1;
}
}
return *this;
}
Date Date::operator+(const int day)const
{
Date tmp = *this;
tmp += day;
return tmp;
}
Date& Date::operator-=(const int day)
{
if (day < 0)
{
return *this += -day;
}
_day -= day;
while(_day <= 0)
{
_month--;
if (_month == 0)
{
_year--;
_month = 0;
}
_day += GetMonthDay(_year, _month);
}
return *this;
}
Date Date::operator-(const int day)const
{
Date tmp = *this;
tmp -= day;
return tmp;
}
//const Date& Date::operator++()
//{
// return *this + 1;
//}
Date& Date::operator++()
{
*this += 1;
return *this;
}
Date Date::operator++(int)
{
Date tmp = *this;
*this += 1;
return tmp;
}
Date& Date::operator--()
{
*this -= 1;
return *this;
}
Date Date::operator--(int)
{
Date tmp = *this;
*this -= 1;
return tmp;
}
int Date::operator-(const Date& date)const
{
Date max = *this;
Date min = date;
int flag = 1;
if (*this < date)
{
max = date;
min = *this;
flag = -1;
}
int count = 0;
while (min != max)
{
min++;
count++;
}
return count * flag;
}
Date& Date::operator=(const Date& date)
{
if (this != &date)//注意用地址比较
{
_year = date._year;
_month = date._month;
_day = date._day;
}
return *this;
}
ostream& operator<<(ostream& out, const Date& date)
{
out << "year:" << date._year << "month:" << date._month << "day:" << date._day << endl;
return out;
}
istream& operator>>(istream& in, Date& date)
{
int year, month, day;
in >> year >> month >> day;
if (month > 0 && month < 13
&& day > 0 && day <= date.GetMonthDay(year, month))
{
date._year = year;
date._month = month;
date._day = day;
}
else
{
perror("非法日期");
assert(false);
}
return in;
}