// to sys_days and local_days constexproperatorsys_days()constnoexcept; constexprexplicitoperatorlocal_days()constnoexcept; constexprboolok()constnoexcept; };
为了和标准库 chrono 交互,提供了 operator sys_days() 的转换
1 2 3
using days = std::chrono::duration <int, std::ratio_multiply<std::ratio<24>, std::chrono::hours::period>>; using sys_days = std::chrono::time_point<std::chrono::system_clock, days>;
to sys_days
1 2 3 4 5 6 7 8 9
TEST_CASE("Year month day object") { auto chloe_dob = date::year_month_day(date::year(2025), date::month(5), date::day(22)); // The construction of year_month_day object may be invalid. REQUIRE(chloe_dob.ok()); auto chloe_dob_tp = date::sys_days(chloe_dob); auto me_dob = date::year_month_day(date::year(1992), date::month(7), date::day(26)); auto me_dob_tp = date::sys_days(me_dob); CHECK_EQ((chloe_dob_tp - me_dob_tp).count(), 11988); }
SUBCASE("add months but invalid") { auto ymd = date::year(2024) / date::month(1) / date::day(30); REQUIRE(ymd.ok()); ymd += date::months(1); CHECK_FALSE(ymd.ok()); } }
adding days
year_month_day 自身不提供对 days 的加减,但是我们可以借用 sys_days 作为中介来完成:
1 2 3 4 5 6
TEST_CASE("Add days to year_month_day") { auto ymd = date::year(2024) / date::month(2) / date::day(29); REQUIRE(ymd.ok()); ymd = date::sys_days(ymd) + date::days(2); CHECK_EQ(ymd, date::year(2024) / date::month(3) / date::day(2)); }
adding days 可以很好的避免结果日期可能是某个不正确的值的情况
Last Day of the Month
利用的是提供的 year_month_day_last 这个类型,常用实践中可以直接构造 year_month_day_last 也可以用 operator/ 搭配常量 last 来方便构造
1 2 3 4 5 6 7 8 9 10 11 12 13 14
TEST_CASE("The last day of the month") { SUBCASE("last day of feb in a leap year is 29") { auto eom = date::year_month_day_last(date::year(2024), date::month_day_last(date::month(2))); REQUIRE(eom.ok()); CHECK_EQ(static_cast<unsigned>(eom.day()), 29); }
SUBCASE("compose last day with more intuitive operator overload") { auto eom = date::year(2025) / date::May / date::last; REQUIRE(eom.ok()); CHECK_EQ(static_cast<unsigned>(eom.day()), 31); } }