CKTIS / C++
std::chrono::year_month_day — dates and validity checks
std::chrono::year_month_day stores year, month, and day fields. Constructing an object does not guarantee a valid date: ok() also checks month length and leap years.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
std::chrono::year_month_day{std::chrono::year{y}, std::chrono::month{m}, std::chrono::day{d}}
constexpr bool std::chrono::year_month_day::ok() const noexcept;std::chrono::year_month_day represents a date using three fields: std::chrono::year denotes the year, std::chrono::month the month, and std::chrono::day the day of the month, not a duration in days. Its constructor accepts these distinct types; year(), month(), and day() return the corresponding fields.
The constructor stores the fields without rejecting nonexistent dates. std::chrono::year_month_day::ok() returns true only when the year and month are valid and the day lies between 1 and the last day of that month in that year. Thus 2024-02-29 is valid, but 2023-02-29 is not. Check ok() before treating input as a valid date.
Adding months or years can produce an invalid date, so check the result again. To add days, convert a valid date to std::chrono::sys_days, add std::chrono::days, then construct a std::chrono::year_month_day. Conversion is not a substitute for validation: an invalid day with a valid year and month is counted relative to the month's beginning; an invalid year or month makes the result unspecified.
Examples
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono;
constexpr year_month_day leap{year{2024}, month{2}, day{29}};
constexpr year_month_day invalid{year{2023}, month{2}, day{29}};
static_assert(leap.ok());
static_assert(!invalid.ok());
constexpr year_month_day next{sys_days{leap} + days{1}};
static_assert(next == year_month_day{year{2024}, month{3}, day{1}});
std::cout << std::boolalpha
<< leap.ok() << ' ' << invalid.ok() << '\n';
std::cout << int(next.year()) << ' '
<< unsigned(next.month()) << ' '
<< unsigned(next.day()) << '\n';
}
Result
true false 2024 3 1
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.