Write a Date class (with leap years) supporting date + days, date - date (days between), ++, <=> and operator<< in DD-MM-YYYY format.
Solution
main.cpp
#include <compare>
#include <iomanip>
#include <iostream>
class Date {
int y_, m_, d_;
static bool leap(int y) { return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; }
static int days_in(int y, int m) {
static const int dm[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return m == 2 && leap(y) ? 29 : dm[m - 1];
}
long serial() const { // days since 1-1-0001
long n = d_;
for (int y = 1; y < y_; ++y) n += leap(y) ? 366 : 365;
for (int m = 1; m < m_; ++m) n += days_in(y_, m);
return n;
}
public:
Date(int d, int m, int y) : y_(y), m_(m), d_(d) {}
Date& operator++() {
if (++d_ > days_in(y_, m_)) { d_ = 1; if (++m_ > 12) { m_ = 1; ++y_; } }
return *this;
}
friend Date operator+(Date a, int days) { while (days-- > 0) ++a; return a; }
friend long operator-(const Date& a, const Date& b) { return a.serial() - b.serial(); }
auto operator<=>(const Date& o) const = default; // year, month, day order
friend std::ostream& operator<<(std::ostream& os, const Date& x) {
return os << std::setfill('0') << std::setw(2) << x.d_ << '-' << std::setw(2) << x.m_ << '-' << x.y_ << std::setfill(' ');
}
};
int main() {
Date exam(20, 2, 2024);
std::cout << exam + 10 << ' ' << exam + 365 << '\n';
Date start(1, 6, 2025), end(15, 8, 2025);
std::cout << end - start << " days, " << (start < end) << ' ' << (Date(1, 1, 2025) - Date(1, 1, 2024)) << '\n';
Date nye(31, 12, 2025);
std::cout << ++nye << '\n';
return 0;
}
Output Verified by compiling and running
01-03-2024 19-02-2025
75 days, 1 366
01-01-2026
2024 is a leap year, so 20 Feb + 10 days is 1 March, and +365 days lands on 19 Feb 2025. Since the members are declared year, month, day, a defaulted <=> orders dates correctly.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!