1. 程式人生 > >兩日期差值計算器(取絕對值)(年月日)

兩日期差值計算器(取絕對值)(年月日)

#include

using namespace std;

class Date
{
private:
int year,month,day;
public:
Date(int i=0,int j=0,int k=0):year(i),month(j),day(k){}
int operator - (Date d);
int fun();

};
int leapyear(int year)
{
if((year%40&&year%100!=0)||year%4000)
return 1;
else
return 0;
}
int fun2(int year1,int year2)//計算兩個年份之間的日期數的差值
{
int i,sum=0;
if(year1>year2)
{
for(i=year2;i<year1;i++)
{
if(leapyear(i))
sum+=366;
else
sum+=365;
}
}
else
{
for(i=year1;i<year2;i++)
{
if(leapyear(i))
sum-=366;
else
sum-=365;
}
}

return sum;

}

int Date::fun()//計算當前是該年的第幾天
{
char m[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int i,sum=0;//未初始化導致隨機值
for(i=0;i<month-1;i++)
sum+=m[i];
if(month>2)
{
if(leapyear(year))
sum+=1;
}
sum+=day;
return sum;
}

int Date::operator-(Date d)
{
int sum=0;
sum+=fun2(year,d.year);//先求出兩個年份之間日期差
sum+=fun()-d.fun();//再求出二者在其年的已走過時間的差,並加上上式即可得出結果
if(sum>0)
return sum;
else
return -sum;
}

int main()
{
int sum;
Date d1(2018,11,10);
Date d2(2014,12,9);
sum = d1-d2;
cout<<sum;

return 0;

}