1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
#include <iostream>
#include <string>
#include "DATE.h"
using namespace std;
const int Date::days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
//Date Constructor
Date::Date(int month, int day, int year)
{
setDate(month, day, year);
}
void Date::setDate(int mm, int dd, int yy)
{
if (mm >= 1 && mm <=12)
month = mm;
else
throw invalid_argument("Month must be 1-12");
if(yy >= 1900 && yy <= 2100)
year = yy;
else
throw invalid_argument("Year must be >= 1900 and <= 2100");
if ((month == 2 && leapYear(year) && dd >= 1 && dd <= 29) ||
(dd >= 1 && dd <= days[month]))
day = dd;
else
throw invalid_argument(
"Day is out of range for current month and year");
}
//overloaded postfix increment operator
Date Date::operator++(int)
{
Date temp = *this;
nextDay();
//return unincremented, saved, temporary object
return temp;
}
//add specified number of days to date
const Date &Date::operator+=(int additionalDays)
{
for (int i = 0; i < additionalDays; ++i)
nextDay();
return *this;
}
//if year is leap year, return true; otherwise, return false
bool Date::leapYear(int testYear)
{
if (testYear % 400 == 0 ||
(testYear % 100 != 0 && testYear % 4 == 0))
return true;
else
return false;
}//end function leapYear
//determine whether the day is the last day of the month
bool Date::endOfMonth(int testDay) const
{
if (month == 2 && leapYear(year))
return testDay == 29;
else
return testDay == days[month];
}
void Date::nextDay()
{
if (!endOfMonth(day))
++day;
else
if (month < 12) //day is end of the month and month < 12
{
++month;
day = 1;
}
else
{
++year;
month = 1;
day = 1;
}
}
//overloaded output operator
ostream &operator<<( ostream &output, const Date &d)
{
static string monthName[13] = { "", "January", "February", "March", "April",
"May", "June", "July", "August", "September", "October", "November", "December"};
output << monthName[d.month]<< ' ' << d.day << ", " << d.year;
return output;
}
void Date::print ()
{
cout << month << '/' << day << '/' << year << endl;
}
|