std::chrono::operator+, std::chrono::operator- (std::chrono::year_month)
來自 cppreference.com
< cpp | chrono | year_month
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 的 duration,如果呼叫會有歧義,則優先使用 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())))
ym1.year() - ym2.year() + std::chrono::months(int(unsigned(ym1.month())) -
int(unsigned(ym2.month())))
[編輯] 注意
兩個 year_month
值相減的結果是 std::chrono::months 型別的 duration。此 duration 單位表示格里高利曆平均月份的長度(30.436875 天),並且生成的 duration 與相關時間段的實際天數無關。例如,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 修改為若干月或若干年(public member function) |