#include "Date.h" Date::Date( ) { setDate( 1, 1, 1600 ); } Date::Date( int m, int d, int y ) { setDate( m, d, y ); } Date::Date( const string & m, int d, int y ) { setDate( MonthInfo::getMonth( m ), d, y ); } void Date::setDate( int m, int d, int y ) { if( m < 0 || m > 12 || y < 1600 || y > 2500 || d < 0 || d > MonthInfo::daysInMonth( m, y ) ) { cerr << "Bad date!! (" << m << " " << d << " " << y << " " << endl; m = 1; d = 1; y = 1600; } month = m; day = d; year = y; } void Date::printDate( ostream & out ) const { out << MonthInfo::getMonth( month ) << " " << day << ", " << year; } bool Date::equals( const Date & rhs ) const { return month == rhs.month && day == rhs.day && year == rhs.year; } bool Date::lessThan( const Date & rhs ) const { if( year != rhs.year ) return year < rhs.year; if( month != rhs.month ) return month < rhs.month; return day < rhs.day; } int Date::daysBetween( const Date & rhs ) const { if( equals( rhs ) ) return 0; if( lessThan( rhs ) ) return - rhs.daysBetween( *this ); // This is the later date! int answer; Date earlier = rhs; for( answer = 0; !equals( earlier ); answer++ ) earlier = earlier.dateAfter( ); return answer; } Date Date::dateAfter( ) const { Date next = *this; if( next.day < MonthInfo::daysInMonth( next.month, next.year ) ) { next.day++; } else { next.day = 1; if( next.month != 12 ) next.month++; else { next.month = 1; next.year++; } } return next; } Date Date::futureDate( int numDays ) const { Date future = *this; if( numDays < 0 ) cerr << "numDays is negative; not the future." << endl; for( int i = 0; i < numDays; i++ ) future = future.dateAfter( ); return future; } bool MonthInfo::isLeapYear( int y ) { return ( y % 400 == 0 ) || ( y % 4 == 0 && y % 100 != 0 ); } int MonthInfo::daysInMonth( int m, int y ) { switch( m ) { case 2: return isLeapYear( y ) ? 29 : 28; case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; default: return 30; } } const string MonthInfo::monthArray[ ] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; int MonthInfo::getMonth( const string & m ) { int i; for( i = 0; i < 12; i++ ) if( monthArray[ i ] == m ) break; return i + 1; } string MonthInfo::getMonth( int m ) { if( m < 1 || m > 12 ) return "???"; else return monthArray[ m - 1 ]; }