I wrote this date class to implement the simple features that some dates might use,
such as the addition and subtraction of a date, and so on, detailed in the code has been marked out.
#include <iostream>
using namespace Std;
Class Date
{
Public
Date (int year = 1900, int month = 1, Int. day = 1)
: _year (year)//initialization list
, _month (month)
, _day (Day)
{
if (Year < 1900
|| Month < 1 | | Month > 12
|| Day < 1 | | Day > Getmonthday (year,month))
{
cout << "Invalid Date" << Endl;
}
}
int Getmonthday (int year, int month)
{
int montharray[12] = {31, 28, 31, 30, 31,
30, 31, 31, 30, 31, 30, 31};
if (Isleapyear (year) &&month==2)
{
return montharray[month-1] + 1;
}
return montharray[month-1];
}
BOOL Isleapyear (int year)
{
Return year% 400 = = 0 | | Year% 4 = = 0
&& Year% 100! = 0;
}
Date operator+ (int day)//plus one number of days
{
Date tmp (*this);
Tmp._day + = day;
while (Tmp._day > Getmonthday (tmp._year,tmp._month))
{
Tmp._day-= Getmonthday (Tmp._year, tmp._month);
if (Tmp._month = = 12)
{
Tmp._year + = 1;
Tmp._month = 1;
}
Else
{
Tmp._month + = 1;
}
}
return TMP;
}
date& operator+= (int day)
{
This->_day + = day;
while (This->_day > Getmonthday (this->_year, This->_month))
{
This->_day-= Getmonthday (This->_year, this->_month);
if (This->_month = = 12)
{
This->_year + = 1;
This->_month = 1;
}
Else
{
This->_month + = 1;
}
}
return *this;
}
Date operator-(int day)//minus one number of days
{
Date tmp (*this);
Tmp._day-= day;
while (Tmp._day < 0)
{
if (Tmp._month = = 1)
{
Tmp._year-= 1;
Tmp._month = 12;
Tmp._day + = Getmonthday (Tmp._year, tmp._month);
}
Else
{
Tmp._month-= 1;
Tmp._day + = Getmonthday (Tmp._year, tmp._month);
}
}
return TMP;
}
Date operator++ ()//forward self-increment
{
*this + = 1;
return *this;
}
BOOL operator== (const date& D)//test Date equal
{
return _year = = d._year&&
_month = = d._month&&
_day = = D._day;
}
BOOL Operator!= (const date& D)
{
Return! (_year = = d._year&&
_month = = d._month&&
_day = = D._day);
}
BOOL operator< (const date& D)
{
Return! (_year < d._year&&
_month < d._month&&
_day < D._day);
}
int operator-(const date& D)//one date minus one date
{
Date TMP1 = D;
Date tmp2 = *this;
int count = 0;
if (TMP2 < TMP1)
{
Date Rev;
Rev = TMP2;
TMP2 = TMP1;
TMP1 = rev;
}
while (tmp2! = TMP1)
{
count++;
++TMP1;
}
return count;
}
void Display ()
{
cout << _year << "-" << _month << "-" << _day << Endl;
}
Private
int _year;
int _month;
int _day;
};
void Test1 ()//test plus or minus a certain number of days
{
int day;
Date D1 (2015,3,1);
D1. Display ();
CIN >> Day;
(D1 + day). Display ();
(D1-day). Display ();
}
void Test2 ()
{
Date D1 (2015, 2, 28);
D1. Display ();
Date D2 (2015, 2, 28);
cout << (D1! = D2) << Endl;
(d1++). Display ();
}
void Test3 ()
{
Date D1 (2004, 2, 1);
Date D2 (2004, 3, 1);
int ret = D1-D2;
cout << ret << Endl;
}
int main ()
{
Test1 ();
Test2 ();
Test3 ();
return 0;
}
A simple date class implemented in C + +