date.h
class date {
private:
int day; // day number: 1-31
int month; // month number: 1-12
int year; // year number: 1901-2099
public:
void set(int d,int m,int y); // set date
bool valid(); // true if date is valid
void print(); // display "Month dd, yyyy"
int year_day(); // day number in current year
int days_1901(); // days since Jan 1,1901
int weekday(); // return weekday number
};
date.cpp
// Implantation of Date Class
#include <iostream.h>
#include "date.h"
void date::set(int d, int m, int y) {
day = d; month = m; year = y;
}
bool date::valid() {
int month_days[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
if (year < 1901 || year > 2099) return false;
if (month < 1 || month > 12) return false;
if (year % 4 == 0) month_days[2] = 29;
if (day < 1 || day > month_days[month]) return false;
return true;
}
void date::print() {
char *name[] = {"", "Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"};
if (!valid()) cout << "Invalid Date\\n";
else cout << name[month] << ' ' << day << ", " << year << endl;
}
int date::year_day() {
if (!valid()) return -1;
int sum_days[] = {0,31,59,90,120,151,181,212,243,273,304,334};
int yr_day = sum_days[month-1]+day;
if (year % 4 == 0 && month > 2) yr_day++;
return yr_day;
}
int date::days_1901() {
if (!valid()) return -1;
return (int) ((year-1901)*365.25 + year_day() – 1);
}
int date::weekday() {
// Sunday = 0, Monday = 1, January 1, 1901 is Tuesday = 2
if (!valid()) return -1;
return (days_1901() + 2) % 7;
}
main.cpp
#include <iostream.h>
#include "date.h"
void main() {
date oneDay;
int d,m,y;
cout << "Enter a day, month, year: "; cin >> d >> m >> y;
oneDay.set(d, m, y);
cout << oneDay.year_day() << endl;
cout << oneDay.days_1901() << endl;
cout << oneDay.weekday() << endl;
oneDay.print();
oneDay.year = 2000;
}