std::chrono...r_month_day)(3)
π NAME π
std::chrono::operator==,(std::chrono::year_month_day) β bestie, it's literally std::chrono::operator==,(std::chrono::year_month_day). That's the whole name. Iconic, honestly. This is a page from the C++ Standard Library docs (the (3) manpage vibe), and we're about to make date comparisons make sense, no cap.
β¨ Synopsis β¨
So this all lives in the header <chrono> π°οΈ β don't forget to include it or nothing works and you'll be sad.
Overload (1) β the equality one, (since C++20):
constexpr bool operator==( const std::chrono::year_month_day& x,
const std::chrono::year_month_day& y )
noexcept;
Overload (2) β the spaceship one π, (since C++20):
constexpr std::strong_ordering
operator<=>( const std::chrono::year_month_day& x,
const std::chrono::year_month_day& y ) noexcept;
π¦ What it actually does
It compares the two year_month_day values x and y. That's it, that's the vibe. π
But okay, the way it compares them is lowkey the main character energy here: it's a lexicographical comparison. That means year() gets checked first, then month(), then day(). Ordered, hierarchal, very organized of it. π
And here's the cheat code: the <, <=, >, >=, and != operators are all synthesized from operator<=> and operator== respectively. So you get all five for free β no extra code, they just appear. Slay. β¨
π Return value π
x.year() == y.year() && x.month() == y.month() && x.day() == y.day()- If
x.year() <=> y.year != 0, thenx.year() <=> y.year; otherwise ifx.month() <=> y.month() != 0, thenx.month() <=> y.month(); otherwisex.day() <=> y.day().
Fr fr, read that second one like a little flowchart: year first, then month if the year tied, then day if the month tied. No skipping steps. π«Ά
πΈ Notes πΈ
Here's the important bit π¨ β if both x and y represent valid dates (that's x.ok() && y.ok() == true), then the result of the lexicographical comparison is consistent with the calendar order. So valid dates sort like actual calendar dates. Beautiful. Chef's kiss. ππ
π Example π
// Run this code
#include <chrono>
int main()
{
constexpr auto ymd1{std::chrono::day(13)/7/1337};
constexpr auto ymd2{std::chrono::year(1337)/7/13};
static_assert(ymd1 == ymd2);
static_assert(ymd1 <= ymd2);
static_assert(ymd1 >= ymd2);
static_assert(ymd1 <=> ymd2 == 0);
}
Not me noticing thatymd1andymd2are written in a different order but still come out equal ππ because the year is1337, the month is7and the day is13in both. The lexicographical order ate. π₯
β Sign-off β
Okay bestie, that's the whole page! π This one came from cppreference.com, dated 2024.06.10, and the source line was std::chrono...r_month_day)(3) β go forth and compare your year_month_days with confidence, you absolute icon. πππ§
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms