#include "Date.h" #include Date::Date(int day, int month, int year) { d = day; m = month; y = year; fix_invalid(); } Date::Date(const Date &o) : d(o.d), m(o.m), y(o.y) {} Date& Date::operator=(const Date &o) { d = o.d; m = o.m; y = o.y; return *this; } Date::~Date() {} void Date::add_days(int n) { if (n<0) { // too hard for me to bother with... } d+=n; int extra_d = d - days_in_month(m,y); while (extra_d>0) { d -= days_in_month(m,y); m+=1; if (m==13) { m=1; y+=1; } extra_d -= days_in_month(m,y); } } int Date::compare(const Date &o) const { if (y < o.y) return -1; else if (y> o.y) return 1; else if (m < o.m) return -1; else if (m > o.m) return 1; else if (d < o.d) return -1; else if (d > o.d) return 1; else return 0; } void Date::fix_invalid() { if (d > days_in_month(m,y)) d = days_in_month(m,y); } int Date::days_in_month(int month, int year) const { static int days[] = {31,28,31,30,31,30,31,31,30,31,30,31}; if (m==2 && leap_year()) return 29; else return days[month-1]; } bool Date::leap_year() const { if (y%4) return false; if (!(y%400)) return true; if (!(y%100)) return false; return true; } int Date::get_day() const { return d; } int Date::get_month() const { return m; } int Date::get_year() const { return y; } const char* Date::day_of_week() const { static const char* days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; int total = 0; int century = y / 100; int ex_year = y % 100; if (y<=1751 || y==1752 && (m<9 || (m==9 && d<=2))) total += 18 - century; else total += (3 - century%4)*2; if (total>=7) total%=7; total += ex_year/12+ex_year%12+(ex_year%12)/4; if (total>=7) total%=7; int month_table[] = {-1,0,3,3,6,36,4,34,2,33,0,31,12}; total+=month_table[m]%7; if (total>=7) total%=7; total+=d; if (m==1 || m==2) if (y%4==0 && (y%100!=0 || y%400==0)) { if (total==0) total+=7; total--; } if (total>=7) total%=7; return days[total]; } const char* Date::month_name() const{ static const char* months[] = { "None", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; return months[m]; } ostream& Date::output(ostream& os) const { return os << day_of_week() << " " << d << " "<< month_name() << " " << y; } ostream& operator<<(ostream& os, const Date &d) { return d.output(os); }