#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <cstdlib>
using namespace std;
//array that stores the number of days for each month of non-leap year
const int DAYSINMONTH[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
class Date
{
private:
int dd;
int mm;
int yy;
bool leapOrNot;
public:
Date (int _dd, int _mm, int _yy)
{
dd = _dd; mm = _mm; yy = _yy;
CheckLeap();
}
int Days(int _dd, int _mm,int _yy)
{
int days = 0;
int leap;
if ((_yy % 4 == 0 && _yy % 100 != 0) || (_yy % 100 == 0 && _yy % 400 == 0)) leap = true;
else
leap = false;
while(_mm > 0)
{
days += DAYSINMONTH[_mm-1];
--_mm;
}
if (leap) days += 1;
--_yy;
while (_yy > 0)
{
if ((_yy % 4 == 0 && _yy % 100 != 0) || (_yy % 100 == 0 && _yy % 400 == 0)) leap = true;
else
leap = false;
if (leap) days += 366;
else
days += 365;
--_yy;
}
days += _dd;
return days;
}
void CheckLeap()
{
if ((yy % 4 == 0 && yy % 100 != 0) || (yy % 100 == 0 && yy % 400 == 0)) leapOrNot = true;
else
leapOrNot = false;
}
Date Date:: operator +(int ndays);
int Date::operator -(Date t);
void DisplayDate()
{
cout<<dd<<"/"<<mm<<"/"<<yy<<endl;
}
};
int main()
{
int dd, mm, yy;
cout<<"Enter the first date (dd, mm, yyyy) : ";
cin>>dd>>mm>>yy;
Date d1(dd, mm, yy);
cout<<"Enter the second date (dd, mm, yyyy) : ";
cin>>dd>>mm>>yy;
Date d2(dd, mm, yy);
int ndays;
ndays = d1 - d2;
cout<<endl<<endl<<"ndays = d1 "<<'-'<<" d2 = "<<ndays<<endl;
d2 = d1 + ndays;
cout<<"d2 = d1 + ndays = ";
d2.DisplayDate();
cout<<endl;
system("pause");
return 0;
}
Date Date::operator +(int ndays)
{
Date date(dd,mm, yy);
date.dd += ndays;
while ( date.dd > DAYSINMONTH[ date.mm-1])
{
if ( date.leapOrNot && date.mm == 2)
{
date.dd -= 29;
++ date.mm;
}
else
{
date.dd -= DAYSINMONTH[ date.mm-1];
++date.mm;
}
if ( date.mm > 12)
{
++ date.yy; date.mm = 1;
date.CheckLeap();
}
}
return date;
}
int Date::operator -(Date t)
{
int x1 = Days(dd, mm, yy);
int x2 = Days(t.dd, t.mm, t.yy);
return x1 - x2 + 1;
}
Comments
Leave a comment