题解 | #日期差值# 日期类秒了
日期差值
https://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c
#include <iostream>
using namespace std;
class Date
{
public:
Date(int year = 0, int month = 0, int day = 0)
:_year(year)
, _month(month)
, _day(day)
{
}
int GetMonthDay(int year, int month)
{
static int tomonth[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;
}
return tomonth[month];
}
bool operator>(const Date& d) const
{
return !(*this <= d);
}
bool operator<(const Date& d) const
{
if (_year < d._year)
{
return true;
}
else if (_year == d._year)
{
if (_month < d._month)
{
return true;
}
else if (_month == d._month)
{
if (_day < d._day)
{
return true;
}
}
}
return false;
}
bool operator<=(const Date& d) const
{
return (*this < d && *this = d);
}
bool operator==(const Date& d) const
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
bool operator!=(const Date& d) const
{
return !(*this == d);
}
Date& operator+=(int day)
{
_day += day;
while (_day > GetMonthDay(_year, _month))
{
if (_month > 12)
{
_year++;
_month = 1;
}
_day -= GetMonthDay(_year, _month);
_month++;
}
return *this;
}
Date& operator++()
{
*this += 1;
return *this;
}
//两个日期相减
int operator-(Date& d) const
{
//假设两日期哪个大
Date max = *this;
Date min = d;
//int flag = 1;
if (max < min)
{
max = d;
min = *this;
//flag = -1;
}
int ret = 0;
while (max != min)
{
ret++;
++min;
}
//ret *= flag;
return ret + 1;
}
int YearToDay()
{
Date ToYear(_year, 1, 1);
// 如果两数相减,得到的是中间的差值;10 - 1 = 9;实际是10天
int Day = 1 + (*this - ToYear);
return Day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
int date1 = 0;
int date2 = 0;
cin >> date1 >> date2;
Date d1(date1 / 10000,(date1 % 10000) / 100,date1 % 100);
Date d2(date2 / 10000,(date2 % 10000) / 100,date2 % 100);
cout << d1 - d2 << endl;
return 0;
}
小天才公司福利 1199人发布