Namespaces
Variants

std::chrono::year_month_day:: operator+=, std::chrono::year_month_day:: operator-=

From cppreference.net

constexpr std:: chrono :: year_month_day &
operator + = ( const std:: chrono :: years & dy ) const noexcept ;
(1) (自 C++20 起)
constexpr std:: chrono :: year_month_day &
operator + = ( const std:: chrono :: months & dm ) const noexcept ;
(2) (自 C++20 起)
constexpr std:: chrono :: year_month_day &
operator - = ( const std:: chrono :: years & dy ) const noexcept ;
(3) (自 C++20 起)
constexpr std:: chrono :: year_month_day &
operator - = ( const std:: chrono :: months & dm ) const noexcept ;
(4) (自 C++20 起)

修改 * this 所表示的时间点,增减时长为 dy dm

1) 等价于 * this = * this + dy ;
2) 等价于 * this = * this + dm ;
3) 等价于 * this = * this - dy ;
4) 等价于 * this = * this - dm ;

对于可同时转换为 std::chrono::years std::chrono::months 的时间段,若调用存在歧义,则优先选择 years 重载 (1,3)

示例

#include <cassert>
#include <chrono>
#include <iostream>
int main()
{
    constexpr auto monthsInYear{12};
    auto ymd{std::chrono::day(1)/std::chrono::July/2020};
    std::cout << "#1 " << ymd << '\n';
    ymd -= std::chrono::years(10);
    std::cout << "#2 " << ymd << '\n';
    assert(ymd.month() == std::chrono::July);
    assert(ymd.year() == std::chrono::year(2010));
    ymd += std::chrono::months(10 * monthsInYear + 11);
    std::cout << "#3 " << ymd << '\n';
    assert(ymd.month() == std::chrono::month(6));
    assert(ymd.year() == std::chrono::year(2021));
    // 处理 ymd += months 的"溢出"情况
    ymd = std::chrono::May/31/2021; // 有效日期
    std::cout << "#4 " << ymd << '\n';
    assert(ymd.ok());
    ymd += std::chrono::months{1}; // 无效日期:6月只有30天
    std::cout << "#5 " << ymd << '\n';
    assert(not ymd.ok());
    assert(ymd == std::chrono::June/31/2021);
    // 对齐到该月最后一天(6月30日):
    const auto ymd1 = ymd.year()/ymd.month()/std::chrono::last;
    std::cout << "#6 " << ymd1 << '\n';
    assert(ymd1.ok());
    assert(ymd1 == std::chrono::June/30/2021);
    // 通过转换为 sys_days 溢出到下个月(7月1日):
    const std::chrono::year_month_day ymd2 = std::chrono::sys_days{ymd};
    std::cout << "#7 " << ymd2 << '\n';
    assert(ymd2.ok());
    assert(ymd2 == std::chrono::July/1/2021);
}

输出:

#1 2020-07-01
#2 2010-07-01
#3 2021-06-01
#4 2021-05-31
#5 2021-06-31 不是有效日期
#6 2021/Jun/last
#7 2021-07-01

参见

year_month_day 进行年或月的加减运算
(函数)