Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://otvet.mail.ru/question/217374813
- #include <iostream>
- using namespace std;
- struct Date {
- int year;
- int month;
- int day;
- Date() : year(1900), month(1), day(1) {}
- Date(int y, int m, int d) : year(y), month(m), day(d) {
- if ((month > 12 || month <= 0 || day <= 0 || year <= 0)
- || (isLeapYear() && day > leap[month])
- || (!isLeapYear() && day > months[month])) {
- year = 1900;
- month = day = 1;
- }
- }
- static const int months[13];
- static const int leap[13];
- bool isLeapYear() {
- bool result;
- if (year % 4 != 0) result = false;
- else if (0 == year % 400) result = true;
- else if (0 == year % 100) result = false;
- else result = true;
- return result;
- }
- int monthDays() {
- if (isLeapYear()) return leap[month];
- return months[month];
- }
- void tonextDate() {
- if (!isLeapYear() && day != months[month]) ++day;
- else if (isLeapYear() && day != leap[month]) ++day;
- else if (month < 12) {
- ++month;
- day = 1;
- } else {
- ++year;
- month = day = 1;
- }
- }
- void toprevDate() {
- if (day != 1) --day;
- else {
- if (month != 1) --month;
- else {
- --year;
- month = 12;
- day = 31;
- }
- if (isLeapYear()) day = leap[month];
- else day = months[month];
- }
- }
- void addDays(int d) {
- if (d <= 0) return;
- for (int i = 0; i < d; ++i) tonextDate();
- }
- void delDays(int d) {
- if (d <= 0) return;
- for (int i = 0; i < d; ++i) toprevDate();
- }
- int cmpDate(Date date) {
- auto is_equal = [this, &date]() {
- return year == date.year && month == date.month && day == date.day;
- };
- auto is_less = [this, &date]() {
- if (year < date.year) return true;
- else if (year == date.year && month < date.month) return true;
- else if (year == date.year && month == date.month && day < date.day) return true;
- return false;
- };
- if (is_equal()) return 0;
- int diff = 0;
- if (is_less()) {
- while (!is_equal()) {
- date.toprevDate();
- ++diff; // если дата, переданная в качестве параметра больше
- }
- } else {
- while (!is_equal()) {
- date.tonextDate();
- --diff; // если дата, переданная в качестве параметра меньше
- }
- }
- return diff;
- }
- friend ostream& operator<<(ostream& out, const Date& date) {
- out << date.year << '-';
- if (date.month < 10) out << '0';
- out << date.month << '-';
- if (date.day < 10) out << '0';
- out << date.day;
- return out;
- }
- };
- const int Date::months[13] = { 365, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
- const int Date::leap[13] = { 366, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
- int main() {
- Date a(2019, 11, 24);
- cout << a << '\n';
- cin.get();
- }
Add Comment
Please, Sign In to add comment