Namespaces
Variants

std::chrono:: operator+, std::chrono:: operator- (std::chrono::year_month)

From cppreference.net
constexpr std:: chrono :: year_month operator + ( const std:: chrono :: year_month & ym,
const std:: chrono :: years & dy ) noexcept ;
(1) (自 C++20 起)
constexpr std:: chrono :: year_month operator + ( const std:: chrono :: years & dy,
const std:: chrono :: year_month & ym ) noexcept ;
(2) (自 C++20 起)
constexpr std:: chrono :: year_month operator + ( const std:: chrono :: year_month & ym,
const std:: chrono :: months & dm ) noexcept ;
(3) (自 C++20 起)
constexpr std:: chrono :: year_month operator + ( const std:: chrono :: months & dm,
const std:: chrono :: year_month & ym ) noexcept ;
(4) (自 C++20 起)
constexpr std:: chrono :: year_month operator - ( const std:: chrono :: year_month & ym,
const std:: chrono :: years & dy ) noexcept ;
(5) (自 C++20 起)
constexpr std:: chrono :: year_month operator - ( const std:: chrono :: year_month & ym,
const std:: chrono :: months & dm ) noexcept ;
(6) (自 C++20 起)
constexpr std:: chrono :: months operator - ( const std:: chrono :: year_month & ym1,
const std:: chrono :: year_month & ym2 ) noexcept ;
(7) (自 C++20 起)
1,2) dy. count ( ) 年添加到 ym
3,4) dm. count ( ) 个月添加到 ym
5) ym 中减去 dy. count ( ) 年。
6) ym 减去 dm. count ( ) 个月。
7) 返回由 ym1 ym2 表示的两个时间点之间相差的月数。

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

目录

返回值

1,2) std:: chrono :: year_month ( ym. year ( ) + dy, ym. month ( ) )
3,4) 一个 year_month z ,使得 z - ym == dm z. ok ( ) == true
5) ym + - dy
6) ym + - dm
7)
ym1. year ( ) - ym2. year ( ) + std:: chrono :: months ( int ( unsigned ( ym1. month ( ) ) ) -
int ( unsigned ( ym2. month ( ) ) ) )

注释

两个 year_month 值相减的结果是类型为 std::chrono::months 的时间长度。该时长单位表示平均格里高利月的长度(30.436875天),所得时长与涉及时间段内的实际天数无关。例如, 2017y / 3 - 2017y / 2 的结果是 std:: chrono :: months ( 1 ) ,即使2017年2月仅包含28天。

示例

#include <cassert>
#include <chrono>
int main()
{
    auto ym{std::chrono::year(2021)/std::chrono::July};
    ym = ym + std::chrono::months(14);
    assert(ym.month() == std::chrono::September);
    assert(ym.year() == std::chrono::year(2022));
    ym = ym - std::chrono::years(3);
    assert(ym.month() == std::chrono::month(9));
    assert(ym.year() == std::chrono::year(2019));
    ym = ym + (std::chrono::September - std::chrono::month(2));
    assert(ym.month() == std::chrono::April);
    assert(ym.year() == std::chrono::year(2020));
}

参见

通过若干月或年修改 year_month 对象
(公开成员函数)