Daily bit(e) of C++ | std::chrono — working with pseudo-dates
Daily bit(e) of C++ #75, The C++20 support for pseudo-dates in the std::chrono library.
When working with dates, it is often convenient to refer to pseudo-dates, such as the last day in March or the second Friday in April.
The C++20 extension to std::chrono
which introduced date manipulation also added support for these constructs.
#include <chrono>
#include <iostream>
using namespace std::chrono;
// Last day for February 2020
auto leap_day = 2020y/February/last;
// decltype(leap_day) == std::chrono::year_month_day_last
// To get the actual date, we need to convert to year_month_day
year_month_day actual_leap_day{leap_day};
// actual == 2020/02/29
// Last Sunday of 2022
auto last_sunday = 2022y/December/Sunday[last];
// decltype(last_sunday) == std::chrono::year_month_weekday_last
// To get the actual date, we need to convert to year_month_day
year_month_day actual_sunday{last_sunday};
// actual_sunday == 2022/12/25
// US Thanksgiving date, 4th Thursday in November
auto thanksgiving = November/Thursday[4];
// decltype(thanksgiving) == std::chrono::month_weekday
for (auto year = 2022y; year < 2027y; year++) {
year_month_day date{thanksgiving/year};
/* Iterate over:
2022-11-24
2023-11-23
2024-11-28
2025-11-27
2026-11-26
*/
}