Untitled
unknown
c_cpp
2 years ago
3.9 kB
10
Indexable
Never
#include <iostream> class Date { public: Date(int, int, int); void setDate(int, int, int); void displayDate() const; Date dateBefore(); Date dateAfter(); private: static bool isValid(int, int, int); static bool isLeapYear(int year); int day; int month; int year; }; Date::Date(int d = 1, int m = 1, int y = 2000) { setDate(d, m, y); } void Date::setDate(int d, int m, int y) { if(isValid(d, m, y)) { day = d; month = m; year = y; } else { std::cout << "Invalid date, setting date to 1/1/2000" << std::endl; day = 1; month = 1; year = 2000; } } void Date::displayDate() const { std::cout << day / 10 << day % 10 << "/" << month / 10 << month % 10 << "/" << year / 1000 << year % 1000 / 100 << year % 100 / 10 << year % 10 << std::endl; } Date Date::dateBefore() { Date d; if (day == 1) { switch (month) { case 1: d.setDate(31, 12, year - 1); break; case 2: case 4: case 6: case 8: case 9: case 11: d.setDate(30, month - 1, year); break; case 3: if (isLeapYear(year)) { d.setDate(29, 2, year); } else { d.setDate(28, 2, year); } break; default: d.setDate(31, month - 1, year); break; } } else { d.setDate(day - 1, month, year); } return d; } bool Date::isValid(int d, int m, int y) { bool valid = true; switch (m) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: if (d > 31 || d < 1) { valid = false; } break; case 2: if (isLeapYear(y)) { if (d > 29 || d < 1) { valid = false; } } else { if (d > 28 || d < 1) { valid = false; } } break; default: if (d > 30 || d < 1) { valid = false; } break; } return valid; } bool Date::isLeapYear(int year) { if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { return true; } else { return false; } } else { return true; } } else { return false; } } Date Date::dateAfter() { Date d; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: if (day == 31) { d.setDate(1, month + 1, year); } else { d.setDate(day + 1, month, year); } break; case 2: if (isLeapYear(year)) { if (day == 29) { d.setDate(1, month + 1, year); } else { d.setDate(day + 1, month, year); } } else { if (day == 28) { d.setDate(1, month + 1, year); } else { d.setDate(day + 1, month, year); } } break; default: if (day == 30) { d.setDate(1, month + 1, year); } else { d.setDate(day + 1, month, year); } break; } return d; } int main() { Date d1(30, 9, 2002); d1.displayDate(); d1.dateBefore().displayDate(); d1.dateAfter().displayDate(); }