# 4399面试题——计算天数

## 算法代码：

class Time
{
private:
int _Year;
int _Month;
int _Day;
const int LEAPYEARDAYS = 366;
const int NONLEAPYEARDAYS = 365;
bool isLeapYear(int year) const;
int daysOfMonth(int month, int year) const;
public:
Time() {}
Time(int y, int m, int d) : _Year(y), _Month(m), _Day(d) {}
~Time() {}
int operator-(const Time & beginTime);
friend istream & operator>>(istream & is, Time & inputTime);
};

bool Time::isLeapYear(int year) const
{
if ((0 == year % 4) && (0 != year % 100)) {
return true;
}
else {
return false;
}
}

int Time::daysOfMonth(int month, int year) const
{
switch (month) {
case 2:
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}

int Time::operator-(const Time & beginTime)
{
int continueDays = 0;

//days between two years
for (int i = 0; i < (this->_Year - beginTime._Year); ++i) {
if (isLeapYear(this->_Year - i)) {
continueDays += LEAPYEARDAYS;
}
else {
continueDays += NONLEAPYEARDAYS;
}
}

//days of this year
for (int i = 1; i < this->_Month; ++i) {
continueDays += daysOfMonth(i, this->_Year);
}
continueDays += this->_Day;

//subtract days of beginTime
for (int i = 1; i < beginTime._Month; ++i) {
continueDays -= daysOfMonth(i, beginTime._Year);
}
continueDays -= beginTime._Day;

return continueDays;
}

istream & operator>>(istream & is, Time & inputTime)
{
is >> inputTime._Year >> inputTime._Month >> inputTime._Day;
return is;
}

## 测试代码：

//
//  main.cpp
//  calculateDays
//
//  Created by Jiajie Zhuo on 2017/4/5.
//

#include <iostream>

using namespace std;

int main(int argc, const char * argv[]) {
Time beginTime(2014, 8, 18);

Time currentTime;
cout << "Please input the current time(year, month, day): ";
cin >> currentTime;

int continueDays;

continueDays = currentTime - beginTime;

cout << "He has been entered for " << continueDays << endl;

return 0;
}