Поделиться через


<chrono> Операторов

operator+

Оператор добавления для следующих типов:

1) 
template <class Rep1, class Period1, class Rep2, class Period2>
constexpr typename common_type<duration<Rep1, Period1>, duration<Rep2, Period2>>::type
   operator+(
      const duration<Rep1, Period1>& Left,
      const duration<Rep2, Period2>& Right);

2)
template <class Clock, class Duration1, class Rep2, class Period2>
constexpr time_point<Clock, typename common_type<Duration1, duration<Rep2, Period2>>::type>
   operator+(
      const time_point<Clock, Duration1>& Time,
      const duration<Rep2, Period2>& Dur);

3)
template <class Rep1, class Period1, class Clock, class Duration2>
time_point<Clock, constexpr typename common_type<duration<Rep1, Period1>, Duration2>::type>
   operator+(
      const duration<Rep1, Period1>& Dur,
      const time_point<Clock, Duration2>& Time);

4)
constexpr day operator+(const day& d, const days& ds) noexcept; // C++20
constexpr day operator+(const days& ds, const day&  d) noexcept; // C++20

5)
constexpr month operator+(const month& m, const months& ms) noexcept; // C++20
constexpr month operator+(const months& ms, const month& m) noexcept; // C++20

6)
constexpr weekday operator+(const weekday& wd, const days& wds) noexcept // C++20
constexpr weekday operator+(const days& ds, const weekday& wd) noexcept; // C++20

7)
constexpr year operator+(const year& y, const years& ys) noexcept; // C++20
constexpr year operator+(const years& ys, const year& y) noexcept; // C++20

8)
constexpr year_month operator+(const year_month& ym, const months& dm) noexcept; // C++20
constexpr year_month operator+(const months& dm, const year_month& ym) noexcept; // C++20
constexpr year_month operator+(const year_month& ym, const years& dy) noexcept; // C++20
constexpr year_month operator+(const years& dy, const year_month& ym) noexcept; // C++20

9)
constexpr year_month_day operator+(const year_month_day& ymd, const months& dm) noexcept; // C++20
constexpr year_month_day operator+(const months& dm, const year_month_day& ymd) noexcept; // C++20
constexpr year_month_day operator+(const year_month_day& ymd, const years& dy) noexcept; // C++20
constexpr year_month_day operator+(const years& dy, const year_month_day& ymd) noexcept; // C++20

10)
constexpr year_month_day_last operator+(const year_month_day_last& ymdl, const months& dm) noexcept; // C++20

11)
constexpr year_month_day_last operator+(const months& dm, const year_month_day_last& ymdl) noexcept; // C++20

12)
constexpr year_month_day_last operator+(const year_month_day_last& ymdl, const years& dy) noexcept; // C++20
constexpr year_month_day_last operator+(const years& dy, const year_month_day_last& ymdl) noexcept; // C++20

13)
constexpr year_month_weekday operator+(const year_month_weekday& ymwd, const months& dm) noexcept; // C++20
constexpr year_month_weekday operator+(const months& dm, const year_month_weekday& ymwd) noexcept; // C++20

14)
constexpr year_month_weekday operator+(const year_month_weekday& ymwd, const years& dy) noexcept; // C++20

15)
constexpr year_month_weekday operator+(const years& dy, const year_month_weekday& ymwd) noexcept; // C++20

16)
constexpr year_month_weekday_last operator+(const year_month_weekday_last& ymwdl, const months& dm) noexcept; // C++20
constexpr year_month_weekday_last operator+(const months& dm, const year_month_weekday_last& ymwdl) noexcept; // C++20

17)
constexpr year_month_weekday_last operator+(const year_month_weekday_last& ymwdl, const years& dy) noexcept; // C++20
constexpr year_month_weekday_last operator+(const years& dy, const year_month_weekday_last& ymwdl) noexcept; // C++20

Возвращаемое значение

1) После преобразования Left и Right их общего типа возвращает duration значение с числом галок, равным сумме преобразованного числа галок.

2-3) Возвращает time_point объект, представляющий точку во времени, которая перемещается интервалом Dur с точки во времени Time.

4) Возвращает результат d+ds.count(). Если результат выходит из диапазона [0, 255], результат не указан.

5) Возвращает результат m+ms.count(). Если результат выходит из диапазона [1, 12], он уменьшается модуло 12, а затем +1.

6) Возвращает результат добавления числа дней и будней в число weekday. Результат будет 7, поэтому всегда в диапазоне [0,6]

7) Возвращает результат добавления года к указанному количеству лет.

8) Возвращает результат добавления количества месяцев и лет в указанный месяц и год.

9) Возвращает результат добавления месяцев или лет в year_month_day. Если ymd.month() он February ymd.day() не находится в диапазоне [1d, 28d], ok() может вернуться false к результату добавления.

10) Возвращает (ymdl.year() / ymdl.month() + dm) / last. Примечание. Используемый / здесь оператор не является оператором деления. Это оператор даты.

11) Возвращает ymdl + dm.

12) Возвращает {ymdl.year()+dy, ymdl.month_day_last()}

13) Возвращается ymwd + dm.count().

14-15) Возвращается {ymwd.year()+dy, ymwd.month(), ymwd.weekday_indexed()}.

16) Возвращает (ymwdl.year() / ymwdl.month() + dm) / ymwdl.weekday_last(). Примечание. Используемый / здесь оператор не является оператором деления, а оператором даты.

17) Возвращает: ymwdl + dy

Пример: operator+

// compile using: /std:c++latest
#include <iostream>
#include <chrono>

using namespace std::chrono;

int main()
{
    // day
    day d{1};
    std::cout << d + days(2) << '\n'; // 03

    // month
    month m{11};
    std::cout << m + months(3)<< '\n'; // Feb

    // weekday
    weekday wd = Thursday;
    std::cout << wd + days(1) << '\n'; // Fri

    // year_month_day_last
    year_month_day_last ymdl{June / last / 2021};
    std::cout << ymdl + years{1} + months{1} << '\n'; // 2022/Jul/last

    // year_month_weekday
    year_month_weekday ymw{ year(1997) / January / Wednesday[1] };
    std::cout << ymw + months{1} << '\n'; // 1997/Feb/Wed[1]
    std::cout << ymw + years{1} << '\n'; // 1998/Jan/Wed[1] 

    // year_month_weekday_last
    year_month_weekday_last ymwl{ year(1997) / January / Wednesday[last] };
    std::cout << ymwl + months{ 1 } << '\n'; // 1997/Feb/Wed[last]
    std::cout << ymwl + years{ 1 } << '\n'; // 1998/Jan/Wed[last] 

    return 0;
}
03
Feb
Fri
2022/Jul/last
1997/Feb/Wed[1]
1998/Jan/Wed[1]
1997/Feb/Wed[last]
1998/Jan/Wed[last]

Одинарный operator+

Примените унарный плюс к следующим типам:

// duration
constexpr common_type_t<duration> operator+() const // C++20

Возвращаемое значение

Возвращает *this.

operator-

Оператор вычитания для следующих типов:

1)
template <class Rep1, class Period1, class Rep2, class Period2>
constexpr typename common_type<duration<Rep1, Period1>, duration<Rep2, Period2>>::type
   operator-(
       const duration<Rep1, Period1>& Left,
       const duration<Rep2, Period2>& Right);
2)
template <class Clock, class Duration1, class Rep2, class Period2>
constexpr time_point<Clock, typename common_type<Duration1, duration<Rep2, Period2>>::type
   operator-(
       const time_point<Clock, Duration1>& Time,
       const duration<Rep2, Period2>& Dur);
3)
template <class Clock, class Duration1, class Duration2>
constexpr typename common_type<Duration1, Duration2>::type
   operator-(
       const time_point<Clock, Duration1>& Left,
       const time_point<Clock, Duration2>& Right);
4)
constexpr day operator-(const day& d,  days& ds) noexcept; // C++20
constexpr day operator-(const day& d, const day& d) noexcept; // C++20

5)
constexpr month operator-(const month& m, const months& ms) noexcept; // C++20
constexpr month operator-(const month& m, const month& ms) noexcept; // C++20

6)
constexpr months operator-(const year_month& Left, const year_month& Right) noexcept; // C++20

7)
constexpr weekday operator-(const weekday& Left, const days& Right) noexcept; // C++20

8)
constexpr days operator-(const weekday& Left, const weekday& Right) noexcept; // C++20

9)
constexpr year operator-(const year& y, const years& ys) noexcept; // C++20

10)
constexpr years operator-(const year& y, const year& y2) noexcept; // C++20

11)
constexpr year_month operator-(const year_month& ym, const months& dm) noexcept; // C++20
constexpr year_month operator-(const year_month& ym, const years& dy) noexcept; // C++20

12)
constexpr year_month_day operator-(const year_month_day& ymd, const months& dm) noexcept; // C++20
constexpr year_month_day operator-(const year_month_day& ymd, const years& dy) noexcept; // C++20

13)
constexpr year_month_day_last operator-(const year_month_day_last& ymdl, const months& dm) noexcept;  // C++20

14)
constexpr year_month_day_last operator-(const year_month_day_last& ymdl, const years& dy) noexcept;  // C++20

15)
constexpr year_month_weekday operator-(const year_month_weekday& ymwd, const months& dm) noexcept; // C++20

16)
constexpr year_month_weekday operator-(const year_month_weekday& ymwd, const years& dy) noexcept; // C++20

17)
constexpr year_month_weekday_last operator-(const year_month_weekday_last& ymwdl, const months& dm) noexcept; // C++20

18)
constexpr year_month_weekday_last operator-(const year_month_weekday_last& ymwdl, const years& dy) noexcept; // C++20

Возвращаемое значение

1) После преобразования длительности, вычитаемой в их общий тип, возвращает duration значение с числом галок, равным количеству тиков, Right вычитаемых из числа тиков.Left

2) Возвращает значение time_point , представляющее точку во времени, которая перемещается с помощью отрицания интервала времени, представленного Durв точке во времени, указанной в параметре Time.

3) Возвращает duration объект, представляющий интервал времени между Left и Right.

4) Возвращает результат d-ds.count(). Если результат выходит из диапазона [0, 255], результат не указан.

5) Если m.ok() == true и ms.ok() == true, возвращает результат вычитания двухмесячных значений или вычитания числа месяцев. Результат будет находиться в диапазоне [1, 12]. Если результат отрицательный, он обертывается вокруг. Например, вычитание одного месяца с января (month m1{1} - months{1}; 12 декабря).

6) Возвращает разницу в месяцах между Left и Right

7) Если Left.ok() == true и Right.ok() == true, возвращается weekday в диапазоне [days{0}, days{6}].

8) Возвращает количество дней между двумя рабочими днями.

9) Возвращает year(int(y)-ys.count)())

10) Возвращает years(int(y) - int(y2)). Вычитание двух year значений приводит к std::chrono::yearsтому, что разница в годах между y и y2. Например, 2021y-2000y выдает years(21).

11) Возвращает результат вычитания месяцев или лет из year_month значения.

12) Возвращает результат вычитания месяцев из year_month_day значения.

13) Возвращает результат вычитания количества месяцев из year_month_day_last значения. По существу: ymdl-dm.

14) Возвращает результат вычитания количества лет из year_month_day_last значения. По существу: ymdl-dy.

15) Возвращает результат вычитания количества месяцев из year_month_weekday значения. По существу: ymwd-dm.

16) Возвращает результат вычитания количества лет из year_month_weekday значения. По существу: ymwd-dy.

17) Возвращает результат вычитания количества месяцев из year_month_weekday_last значения. По существу: ymwdl-dm.

18) Возвращает результат вычитания количества лет из year_month_weekday_last значения. По существу: ymwdl-dy.

Пример: operator-

// compile using: /std:c++latest
#include <iostream>
#include <chrono>

using namespace std::chrono;

int main()
{
    // day
    day d{10};
    d = d - days(5);  
    std::cout << d << '\n'; // 05

    // month 
    month m{2};
    m = m - months{1};
    std::cout << m << '\n'; // Jan
    m = m - months{1};
    std::cout << m << '\n'; // Dec

    // year
    auto diff1 = 2021y-2000y;
    auto diff2 = 2021y-years{1};
    std::cout << diff1.count() << '\n'; // 21
    std::cout << diff2 << '\n'; // 2020

    // year_month
    const year theYear{ 2021 };
    year_month ym1{theYear, June};
    year_month ym2 = ym1 - months{2};
    std::cout << ym2 << '\n'; // 2021/Apr
    year_month ym3 = ym1 - years{2};
    std::cout << ym3 << '\n'; // 2019/Jun

    // year_month_day_last
    year_month_day_last ymdl = June / last / 2021;
    std::cout << ymdl - years{1} - months{1} << '\n'; // 2022/Jul/last

    // year_month_weekday
    year_month_weekday ymw{ year(1997) / January / Wednesday[1] };
    std::cout << ymw - months{1} << '\n'; // 1996/Dec/Wed[1]
    std::cout << ymw - years{1} << '\n'; // 1996/Jan/Wed[1] 

    // year_month_weekday_last
    year_month_weekday_last ymwl{ year(1997) / January / Wednesday[last] };
    std::cout << ymwl - months{ 1 } << '\n'; // 1996/Dec/Wed[last]
    std::cout << ymwl - years{ 1 } << '\n'; // 1996/Jan/Wed[last]
    
    return 0;
}
05
Jan
Dec
21
2020
2021/Apr
2019/Jun
2020/May/last
1996/Dec/Wed[1]
1996/Jan/Wed[1]
1996/Dec/Wed[last]
1996/Jan/Wed[last]

Одинарный operator-

Отрицает duration.

constexpr common_type_t<duration> operator-() const;

Возвращаемое значение

Возвращает отрицаемую копию *this

Пример: унарный operator-

// compile using: /std:c++latest
#include <iostream>
#include <chrono>

using namespace std::chrono;

int main()
{
   duration<int, std::milli> milliseconds(120);
   std::cout << -milliseconds << '\n';
   return 0;
}
-120ms

operator!=

Определяет, следует ли:

1) Два duration объекта не представляют одинаковое количество галок.
2) Два time_point объекта не представляют один и тот же момент времени.

1)
template <class Rep1, class Period1, class Rep2, class Period2>
constexpr bool operator!=(
    const duration<Rep1, Period1>& Left,
    const duration<Rep2, Period2>& Right);

2)
template <class Clock, class Duration1, class Duration2>
constexpr bool operator!=(
    const time_point<Clock, Duration1>& Left,
    const time_point<Clock, Duration2>& Right);

Параметры

Left
Левый объект duration или объект time_point.

Right
Правый объект duration или объект time_point.

Возвращаемое значение

1) Возвращает значение true , если число тиков для типа общего Left Right и не равно. В противном случае возвращается false.
2) Возвращает, true если два time_point объекта не представляют одинаковый момент времени. В противном случае возвращается false.

operator*

Оператор умножения для объектов duration. После преобразования durationпреобразуемых значений с умножением на их общий тип возвращает duration значение с числом галок, равным умножению преобразованного числа галок.

1)
template <class Rep1, class Period1, class Rep2>
constexpr duration<typename common_type<Rep1, Rep2>::type, Period1>
   operator*(
      const duration<Rep1, Period1>& Dur,
      const Rep2& Mult);

2)
template <class Rep1, class Rep2, class Period2>
constexpr duration<typename common_type<Rep1, Rep2>::type, Period2>
   operator*(
       const Rep1& Mult,
       const duration<Rep2,
       Period2>& Dur);

Параметры

Dur
Объект duration.

Mult
Целочисленное значение.

Возвращаемое значение

duration Возвращает объект, длина интервала которого умножается Mult на длинуDur.

1) Если is_convertible<Rep2, common_type<Rep1, Rep2>>не содержится true, эта функция не участвует в разрешении перегрузки. Дополнительные сведения см. в type_traits><.

2) Если is_convertible<Rep1, common_type<Rep1, Rep2>>не содержится true, эта функция не участвует в разрешении перегрузки. Дополнительные сведения см. в type_traits><.

operator<

1) После преобразования durations по сравнению с их общим типом определяет, меньше ли количество клещей Left для Right.

2) Определяет, находится ли точка во времени с эпохи Lefttime_point меньше времени с эпохи.Righttime_point

1)
template <class Rep1, class Period1, class Rep2, class Period2>
constexpr bool operator<(
    const duration<Rep1, Period1>& Left,
    const duration<Rep2, Period2>& Right);

2)
template <class Clock, class Duration1, class Duration2>
constexpr bool operator<(
    const time_point<Clock, Duration1>& Left,
    const time_point<Clock, Duration2>& Right);

Параметры

Left
Левый объект duration или объект time_point.

Right
Правый объект duration или объект time_point.

Возвращаемое значение

1) Возвращает true , если число галок Left для меньше числа тиков Right. В противном случае функция возвращает значение false.

2) Возвращается true , если Left предшествует Right. В противном случае возвращается false.

operator<=

1) После преобразования durations по сравнению с их общим типом определяет, меньше ли число клещей Left для меньшего числа или совпадает Right.

2) Определяет, является ли точка во времени эпохи Lefttime_point меньше или равной времени с момента эпохи time_point в Right.

1)
template <class Rep1, class Period1, class Rep2, class Period2>
constexpr bool operator<=(
    const duration<Rep1, Period1>& Left,
    const duration<Rep2, Period2>& Right);

2)
template <class Clock, class Duration1, class Duration2>
constexpr bool operator<=(
    const time_point<Clock, Duration1>& Left,
    const time_point<Clock, Duration2>& Right);

Параметры

Left
Левый объект duration или объект time_point.

Right
Правый объект duration или объект time_point.

Возвращаемое значение

1) Возвращает true , если число галок Left меньше или равно количеству тиков Right. В противном случае функция возвращает значение false.

2) Возвращается true , если Left предшествует или равно, Right. В противном случае возвращается false.

operator==

Определяет, следует ли:

1) duration объекты представляют интервалы времени с одинаковой длиной.
2) time_point объекты представляют тот же момент времени.
3) day объекты представляют тот же день.
4) month объекты представляют тот же месяц.
5) month_day объекты представляют один месяц и день.
6) month_day_last объекты представляют тот же месяц.
7) month_weekday объекты представляют тот же месяц и nth weekday.
8) month_weekday_last объекты представляют тот же месяц и последний день недели.
9) weekday объекты представляют тот же день недели.
10) weekday_last объекты представляют тот же последний день недели месяца.
11) weekday_indexed представляет тот же индекс дня недели.
12) year представляет тот же год.
13) year_month представляет один и тот же год и месяц.
14) year_month_day представляет один и тот же год, месяц и день.
15) year_month_day_last представляет тот же последний день года и месяца.
16) year_month_weekday представляют тот же день недели, год и месяц.
17) year_month_weekday_last представляют тот же последний день недели месяца, года и месяца.
18) time_zone_link имеют то же самое name. Имя target не считается.
19) zoned_time представляют одинаковый часовой пояс и часовой пояс.

// 1) duration<Rep, Period>
template <class Rep1, class Period1, class Rep2, class Period2>
constexpr bool operator==(
    const duration<Rep1, Period1>& Left,
    const duration<Rep2, Period2>& Right);

// 2) time_point
template <class Clock, class Duration1, class Duration2>
constexpr bool operator==(
    const time_point<Clock, Duration1>& Left,
    const time_point<Clock, Duration2>& Right);

// 3) day
constexpr bool operator==(const day& Left, const day& Right) noexcept; // C++20

// 4) month
constexpr bool operator==(const month& Left, const month& Right) noexcept; // C++20

// 5) month_day
constexpr bool operator==(const month_day& Left, const month_day& Right) noexcept; // C++20

// 6) month_day_last
constexpr bool operator==(const month_day_last& Left, const month_day_last& Right) noexcept; // C++20

// 7) month_weekday
constexpr bool operator==(const month_weekday& Left, const month_weekday& Right) noexcept; // C++20

// 8) month_weekday_last
constexpr bool operator==(const month_weekday_last& Left, const month_weekday_last& Right) noexcept; // C++20

// 9) weekday
constexpr bool operator==(const weekday& Left, const weekday& Right) noexcept; // C++20

// 10) weekday_last
constexpr bool operator==(const weekday_last& Left, const weekday_last& Right) noexcept; // C++20

// 11) weekday_indexed
constexpr bool operator==(const weekday_indexed& x, const weekday_indexed& y) noexcept; // C++20

// 12) year
constexpr bool operator==(const year& Left, const year& y ) noexcept; // C++20

// 13) year_month
constexpr bool operator==(const year_month& Left, const year_month& Right) noexcept; // C++20

// 14) year_month_day
constexpr bool operator==(const year_month_day& Left, const year_month_day& Right) noexcept; // C++20

// 15) year_month_day_last
constexpr bool operator==(const year_month_day_last& Left, const year_month_day_last& Right) noexcept; // C++20

// 16) year_month_weekday
constexpr bool operator==(const year_month_weekday& Left, const year_month_weekday& Right) noexcept; // C++20

// 17)  year_month_weekday_last
constexpr bool operator==(const year_month_weekday_last& Left, const year_month_weekday_last& Right) noexcept; // C++20

// 18) time_zone_link
bool operator==(const time_zone_link& Left, const time_zone_link& Right) noexcept; // C++20

// 19) zoned_time
template <class Duration1, class Duration2, class TimeZonePtr>
bool operator==(const zoned_time<Duration1, TimeZonePtr>& Left, const zoned_time<Duration2, TimeZonePtr>& Right); // C++20

Параметры

Left
Левый объект для сравнения, например Left == Right

Right
Правый из сравниваемых объектов.

Возвращаемое значение

1) Возвращает true значение, если число тиков для типа общего Left типа и Right равно. В противном случае возвращается false.
2) Возвращает значение true , если Left и Right представляет тот же момент времени. В противном случае возвращается false.
3-17) Возвращает true значение, если Left и Right имеет то же значение. В противном случае возвращается false.
18) Возвращает true значение if Left.name() == Right.name(). В противном случае возвращается *false*.
19) Возвращается true , если Left.get_time_zone() == _Right.get_time_zone() && Left.get_sys_time() == Right.get_sys_time();

operator>

1) После преобразования durations по сравнению с их общим типом определяет, больше ли число клещей Left для Right.

2) Определяет, является ли момент времени с эпохи Lefttime_point больше времени с момента эпохи.Righttime_point

1) 
template <class Rep1, class Period1, class Rep2, class Period2>
constexpr bool operator>(
    const duration<Rep1, Period1>& Left,
    const duration<Rep2, Period2>& Right);

2)
template <class Clock, class Duration1, class Duration2>
constexpr bool operator>(
    const time_point<Clock, Duration1>& Left,
    const time_point<Clock, Duration2>& Right);

Параметры

Left
Левый объект duration или объект time_point.

Right
Правый объект duration или объект time_point.

Возвращаемое значение

1) Возвращает true , если число галок Left больше, чем число галок для Right. В противном случае функция возвращает значение false.

2) Возвращается true , если Left происходит после Right. В противном случае возвращается false.

operator>=

1) После преобразования durations по сравнению с их общим типом определяет, больше ли число тиков Left больше или равно Right.

2) Определяет, является ли точка во времени эпохи Lefttime_point больше или равной времени с момента эпохи time_point в Right.

1)
template <class Rep1, class Period1, class Rep2, class Period2>
constexpr bool operator>=(
    const duration<Rep1, Period1>& Left,
    const duration<Rep2, Period2>& Right);

2)
template <class Clock, class Duration1, class Duration2>
constexpr bool operator>=(
    const time_point<Clock, Duration1>& Left,
    const time_point<Clock, Duration2>& Right);

Параметры

Left
Левый объект duration или объект time_point.

Right
Правый объект duration или объект time_point.

Возвращаемое значение

1) Возвращаетtrue, если число галок Left больше или равно количеству тиков.Right В противном случае функция возвращает значение false.

2) Возвращается true , если Left происходит после или равно, Right. В противном случае возвращается false.

operator<=>

Оператор космического корабля с operator==синтезирует операторы для <, <=, >>=и != для следующих типов:

1)
constexpr bool operator<=>(const day& Left, const day& Right) noexcept; // C++20

constexpr std::strong_ordering operator<=>(const month& Left, const month& Right) noexcept; // C++20

constexpr strong_ordering operator<=>(const month_day& Left, const month_day& Right) noexcept; // C++20

constexpr std::strong_ordering operator<=>(const year& Left, const year& Right ) noexcept; // C++20

constexpr strong_ordering operator<=>(const year_month& Left, const year_month& Right) noexcept; // C++20

template<class Clock, class Duration1, three_­way_­comparable_­with<Duration1> Duration2>
    constexpr auto operator<=>(const time_point<Clock, Duration1>& Left, const time_point<Clock, Duration2>& Right); // C++20

template<class Rep1, class Period1, class Rep2, class Period2>
  requires three_­way_­comparable<typename CT::rep>
    constexpr auto operator<=>(const duration<Rep1, Period1>& Left, const duration<Rep2, Period2>& Right);

2)
constexpr strong_ordering operator<=>(const month_day_last& Left, const month_day_last& Right) noexcept;

3)
constexpr strong_ordering operator<=>(const year_month_day_last& Left, const year_month_day_last& Right) noexcept;

4)
strong_ordering operator<=>(const time_zone_link& Left, const time_zone_link& Right) noexcept;

Параметры

Left, Right
, daymonthyear_monthyear_month_daydurationmonth_day_lastyear_month_day_last month_daytime_pointtime_zone_linkyearчтобы сравнить.

Возвращаемое значение

1)
0 если Left == Right
< 0 если Left < Right
> 0 если Left > Right

2)
Эквивалентно: Left.month() <=> Right.month()

3)
Эквивалентно:

if (auto c = Left.year() <=> Right.year(); c != 0) return c;
return Left.month_day_last() <=> Right.month_day_last();

4)
Эквивалентно:

Left.name() <=> Right.name()

Пример: operator<=>

// compile using: /std:c++latest
#include <iostream>
#include <chrono>

using namespace std::chrono; // for day and 'd' literals

int main()
{
    day d1{3};
    day d2{2};

    if ((d1 <=> d2) == 0)
    {
        std::cout << "equal\n";
    }
    else if ((d1 <=> d2) < 0)
    {
        std::cout << "d1 < d2\n";
    }
    else if ((d1 <=> d2) > 0)
    {
        std::cout << "d1 > d2\n";
    }

    std::cout << std::boolalpha << (1d <= 1d) << ' ' << (1d != 2d) << ' ' << (2d > 3d);

    return 0;
}
d1 < d2
true true false 

operator<<

Выводит следующие типы в поток:

// 1) day
template <class CharT, class Traits>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os, const day& d); // C++20

// 2) hh_mm_ss
template<class CharT, class traits, class Duration>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const hh_mm_ss<Duration>& hms); // C++20

// 3) month
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const month& m); // C++20

// 4) month_day
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const month_day& md); // C++20

// 5) month_day_last
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const month_day_last& mdl); // C++20

// 6) month_weekday
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const month_weekday& mwd); // C++20

// 7) month_weekday_last
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const month_weekday_last& mwdl); // C++20

// 8) weekday
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const weekday& wd); // C++20

// 9) weekday_indexed
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const weekday_indexed& wdi); // C++20

// 10) weekday_last
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const weekday_last& wdl); // C++20

// 11) year
template <class CharT, class Traits>
std::basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const year& y); // C++20

// 12) year_month
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const year_month& ym); // C++20

// 13) year_month_day
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const year_month_day& ymd); // C++20

// 14) year_month_day_last
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const year_month_day_last& ymdl); // C++20

// 15) year_month_weekday
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const year_month_weekday& ymwd); // C++20

// 16) year_month_weekday_last
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const year_month_weekday_last& ymwdl); // C++20

// 17) tai_time
template<class CharT, class Traits, class Duration>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const tai_time<Duration>& t); // C++20

// 18) utc_time
template<class CharT, class Traits, class Duration>
basic_ostream<CharT, traits>&
operator<<(basic_ostream<CharT, Traits>& os, const utc_time<Duration>& t); // C++20

// 19) gps_time
template<class CharT, class Traits, class Duration>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const gps_time<Duration>& t); // C++20

// 20) local_time
template<class CharT, class Traits, class Duration>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const local_time<Duration>& t); // C++20

// 21) sys_info
template<class CharT, class Traits>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const sys_info& si);

// 22) local_info
template<class CharT, class Traits>
basic_ostream<charT, traits>&
operator<<(basic_ostream<CharT, Traits>& os, const local_info& li);

// 23) zoned_time
template<class CharT, class Traits, class Duration, class TimeZonePtr>
basic_ostream<CharT, Traits>&
operator<<(basic_ostream<CharT, Traits>& os, const zoned_time<Duration, TimeZonePtr>& zt);

Параметры

CharT
Тип данных одного символа, считываемого из потока и хранящегося в строке. Стандартная библиотека C++ предоставляет специализации этого шаблона класса с определениями string типов для элементов типаchar, wstringдля , для , u16string для wchar_tchar16_tи u32string для char32_t.

Traits
CharT Описывает атрибуты для basic_string и basic_istream специализации.

os
Выходной поток, в который будет выведено day значение.

d
Выходные day данные.

hms
Выходные hh_mm_ss данные.

li
Выходные local_info данные.

m
Выходные month данные.

md
Выходные month_day данные.

mdl
Выходные month_day_last данные.

mwd
Выходные month_weekday данные.

mwdl
Выходные month_weekday_last данные.

si
Выходные sys_info данные.

t
, или gps_timetai_timeutc_time выходные local_timeданные.

TimeZonePtr
Указатель на time_zone , хранящийся в элементе zoned_time.

wd
Выходные weekday данные.

wdi
Выходные weekday_indexed данные.

wdl
Выходные weekday_last данные.

y
Выходные year данные.

ym
Выходные year_month данные.

ymd
Выходные year_month_day данные.

ymdl
Выходные year_month_day_last данные.

ymwd
Выходные year_month_weekday данные.

ymwdl
Выходные year_month_weekday_last данные.

zt
Выходные zoned_time данные.

Возвращаемое значение

Исходящий поток, который вы передали, os

Замечания

1) day Значение выводится как десятичное число с начальным нулем, если результат будет одной цифрой. Если !d.ok()значение "не является допустимым днем", добавляется к выходным данным.

2) Значение hh_mm_ss выводится в виде часов:минут:секунд:тысячных секунд. Например, "00:00:05.721"

3) Сокращенное имя месяца с использованием языкового стандарта, связанного с os, является выходным. Например, Jan. Если !m.ok(), то " is not a valid month" добавляется к выходным данным.

4) Сокращенное имя месяца с использованием языкового стандарта, связанного с osдатой, с начальным нулем, если результат будет одной цифрой, является выходным. Например, Jan/05. Если !md.ok(), то " is not a valid month" может быть добавлено к выходным данным месяца и "is not a valid day" может быть добавлено к выходным данным дня. Например, 204 is not a valid month/204 is not a valid day.

5) Сокращенное имя месяца, используя языковой стандарт, связанный с os, а затем /last. Например, Jan/last.

6) Сокращенное имя дня недели, используя языковой стандарт, связанный с os, а затем nth weekday в месяце он представляет в скобках. Например, Mon[1].

7) Сокращенное имя дня недели, используя языковой стандарт, связанный с os, за которым следует последний рабочий день месяца, который он представляет в скобках. Например, Jan/Mon[last].

8) Сокращенное имя дня недели с использованием языкового стандарта, связанного с os, выводится. Если !wd.ok(), то " is not a valid weekday" добавляется к выходным данным.

9) Сокращенное имя дня недели, использующий языковой стандарт, связанный с os, выводится, а затем будний день месяца в скобках. Например, Mon[3]. Если !wd.ok(), то " is not a valid weekday" может быть добавлено в день выходных данных недели и "is not a valid index" может быть добавлено к выходным данным индекса недели.

10) Последний рабочий день месяца, используя языковой стандарт, связанный с os, выводится, за которым следует [last]дата. Например, Tue[last] 2019-10-29. Если !wd.ok(), то " is not a valid weekday" может быть добавлено в день выходных данных недели и "is not a valid index" может быть добавлено к выходным данным индекса недели.

11) Год слева от 0 (ноль) до четырех цифр, если результат будет меньше этого. Если !y.ok(), то " is not a valid year" добавляется к выходным данным.

12) Выходные year_month данные в форме гггг-мм-дд. Если ym.ok возвращается false, " is not a valid date" добавляется.

13) Выходные year_month_day данные в форме гггг-мм-дд. Если ymd.ok возвращается false, " is not a valid date" добавляется.

14) Выходные year_month_day_last данные в форме гггг/месяц/последний. Например, 2020/May/last.

15) Выходные year_month_weekday данные в форме yy/month/weekday[index]. Например: 1996/Jan/Wed[1]

16) Выходные year_month_weekday_last данные в форме yy/month/weekday[last]. Например: 1996/Jan/Wed[last]

17) Выходные tai_time данные в форме гггг-мм-дд чч:мм:ss.sss. Например: 2021-08-13 23:23:08.4358666

18) Выходные utc_time данные в форме гггг-мм-дд чч:мм:ss.sssss. Например: 2021-08-13 23:23:08.4358666

19) Выходные gps_time данные в форме гггг-мм-дд чч:мм:ss.sss. Например: 2021-08-13 23:23:08.4358666

20) Выходные local_time данные в виде количества секунд с момента эпохи часов. Это выходные данные, как будто.os << std::chrono::sys_time<Duration>(some_local_time.time_since_epoch()); Например, если some_local_time 18 августа 2021 г. 3:13 вечера, выходные данные будут 1597792380.

21) В реализации sys_info Корпорации Майкрософт выходные данные в виде beginего полей , endи offsetsaveabbrev полей. Например: begin: 2021-03-14 10:00:00, end: 2021-11-07 09:00:00, offset: -25200s, save: 60min, abbrev: PDT

22) В реализации local_info Корпорации Майкрософт выходные данные в виде гггг-мм-дд чч:мм::ss.ss. Например: 2021-09-17 13:55:59.6590120

23) Местное время в zoned_time (полученном как zt.get_local_time()) выводится с помощью часового пояса гггг-мм-дд чч:мм:сс. Например: 2021-09-15 10:45:00 GMT-6

Пример: operator<<

// compile using: /std:c++latest
#include <iostream>
#include <chrono>

using namespace std::chrono;

int main()
{
    std::cout << utc_clock::now() << '\n';

    year_month ym{ 2021y / April };
    std::cout << ym;
    return 0;
}
2021-08-16 20:47:05.6299822
2021/Apr

operator modulo

Оператор для операций durationс модулем.

1)
template <class Rep1, class Period1, class Rep2>
constexpr duration<Rep1, Period1, Rep2>::type
   operator%(
      const duration<Rep1, Period1>& Dur,
      const Rep2& Div);

2)
template <class Rep1, class Period1, class Rep2, class Period2>
constexpr typename common_type<duration<Rep1, _Period1>, duration<Rep2, Period2>>::type
   operator%(
     const duration<Rep1, Period1>& Left,
     const duration<Rep2, Period2>& Right);

Параметры

Dur
Объект duration.

Div
Целочисленное значение.

Left
Делимое. Модуль является оставшимся после деления дивиденда делителем.

Right
duration Правый объект, делитель.

Возвращаемое значение

1) Возвращает объект, длина интервала duration которого является Dur модулем Div.

2) Возвращает значение, представляющее Left модуло Right.

operator/ для duration

Оператор деления для объектов duration.

1)
template <class Rep1, class Period1, class Rep2>
constexpr duration<typename common_type<Rep1, Rep2>::type, Period1>
   operator/(
     const duration<Rep1, Period1>& Dur,
     const Rep2& Div);

2)
template <class Rep1, class Period1, class Rep2, class Period2>
constexpr typename common_type<Rep1, Rep2>::type
   operator/(
     const duration<Rep1, Period1>& Left,
     const duration<Rep2, Period2>& Right);

Параметры

Dur
Объект duration.

Div
Целочисленное значение.

Left\w Левый duration объект.

Right
Правой объект duration.

Возвращаемое значение

1) Объект длительности, длина интервала Dur которого составляет длину, разделенную на значение Div.

2) Соотношение длины интервала Left и Right.

Если is_convertible<Rep2, common_type<Rep1, Rep2>>не имеет значения true и Rep2 не является экземпляром экземпляра duration, первый оператор не участвует в разрешении перегрузки. Дополнительные сведения см. в type_traits><.

operator/ для дат календаря

Предоставляет синтаксис для создания дат календаря в следующих формах:

месяц/день/год
day/month/year
год/месяц/день

День можно заменить следующим:

last
weekday[n] для n-го дня месяца
weekday[last] за последний weekday месяц.

Частичные даты можно сформировать следующим образом:

year_month ym = 2015y/April;
month_day md1 = April/4;
month_day md2 = 4d/April;

Целые числа можно использовать, если интерпретация не является неоднозначной.

/////////  returns year_month

// 1
constexpr year_month
operator/(const year& y, const month& m) noexcept; // C++20

// 2
constexpr year_month
operator/(const year& y, int m) noexcept; // C++20
 
/////////  returns month_day

// 3
constexpr month_day
operator/(const month& m, const day& d) noexcept; // C++20

// 4
constexpr month_day
operator/(const month& m, int d) noexcept; // C++20

// 5
constexpr month_day
operator/(int m, const day& d) noexcept; // C++20

// 6
constexpr month_day
operator/(const day& d, const month& m) noexcept; // C++20

// 7
constexpr month_day
operator/(const day& d, int m) noexcept; // C++20

/////////  returns month_day_last

// 8
constexpr month_day_last
operator/(const month& m, last_spec) noexcept; // C++20

// 9
constexpr month_day_last
operator/(int m, last_spec) noexcept; // C++20

// 10
constexpr month_day_last
operator/(last_spec, const month& m) noexcept; // C++20

// 11
constexpr month_day_last
operator/(last_spec, int m) noexcept; // C++20

/////////  returns month_weekday

// 12
constexpr month_weekday
operator/(const month& m, const weekday_indexed& wdi) noexcept; // C++20

// 13
constexpr month_weekday
operator/(int m, const weekday_indexed& wdi) noexcept; // C++20

// 14
constexpr month_weekday
operator/(const weekday_indexed& wdi, const month& m) noexcept; // C++20

// 15
constexpr month_weekday
operator/(const weekday_indexed& wdi, int m) noexcept; // C++20

/////////  returns month_weekday_last

// 16
constexpr month_weekday_last
operator/(const month& m, const weekday_last& wdl) noexcept; // C++20

// 17
constexpr month_weekday_last
operator/(int m, const weekday_last& wdl) noexcept; // C++20

// 18
constexpr month_weekday_last
operator/(const weekday_last& wdl, const month& m) noexcept; // C++20

// 19
constexpr month_weekday_last
operator/(const weekday_last& wdl, int m) noexcept; // C++20

/////////  returns year_month_day

// 20
constexpr year_month_day
operator/(const year_month& ym, const day& d) noexcept; // C++20

// 21
constexpr year_month_day
operator/(const year_month& ym, int d) noexcept; // C++20

// 22
constexpr year_month_day
operator/(const year& y, const month_day& md) noexcept; // C++20

// 23
constexpr year_month_day
operator/(int y, const month_day& md) noexcept; // C++20

// 24
constexpr year_month_day
operator/(const month_day& md, const year& y) noexcept; // C++20

// 25
constexpr year_month_day
operator/(const month_day& md, int y) noexcept; // C++20

/////////  returns year_month_day_last

// 26
constexpr year_month_day_last
operator/(const year_month& ym, last_spec) noexcept; // C++20

// 27
constexpr year_month_day_last
operator/(const year& y, const month_day_last& mdl) noexcept; // C++20

// 28
constexpr year_month_day_last
operator/(int y, const month_day_last& mdl) noexcept; // C++20

// 29
constexpr year_month_day_last
operator/(const month_day_last& mdl, const year& y) noexcept; // C++20

// 30
constexpr year_month_day_last
operator/(const month_day_last& mdl, int y) noexcept; // C++20

/////////  returns year_month_weekday

// 31
constexpr year_month_weekday
operator/(const year_month& ym, const weekday_indexed& wdi) noexcept; // C++20

// 32
constexpr year_month_weekday
operator/(const year& y, const month_weekday& mwd) noexcept; // C++20

// 33
constexpr year_month_weekday
operator/(int y, const month_weekday& mwd) noexcept; // C++20

// 34
constexpr year_month_weekday
operator/(const month_weekday& mwd, const year& y) noexcept; // C++20

// 35
constexpr year_month_weekday
operator/(const month_weekday& mwd, int y) noexcept; // C++20

/////////  returns year_month_weekday_last

// 36
constexpr year_month_weekday_last
operator/(const year_month& ym, const weekday_last& wdl) noexcept; // C++20

// 37
constexpr year_month_weekday_last
operator/(const year& y, const month_weekday_last& mwdl) noexcept; // C++20

// 38
constexpr year_month_weekday_last
operator/(int y, const month_weekday_last& mwdl) noexcept; // C++20

// 39
constexpr year_month_weekday_last
operator/(const month_weekday_last& mwdl, const year& y) noexcept; // C++20

// 40
constexpr year_month_weekday_last
operator/(const month_weekday_last& mwdl, int y) noexcept; // C++20

Параметры

d
День. Предоставлено либо в виде целого числа в диапазоне [1,31], либо как целое dayчисло.

lastspec
Пустой тип тега, указывающий последний элемент в последовательности. Например, 2021y/May/last это последний день мая 2021 года.

m
Месяц. Предоставляется либо как целое число в диапазоне [1,12], либо в виде month.

md
Месяц и день.

mdl
Последний день указанного месяца.

mwd
N-й день недели указанного месяца.

mwdl
Последний рабочий день указанного месяца.

wdi
Индекс дня недели (weekday_indexed). Например, weekday_indexed(Monday, 1) это первый понедельник месяца.

wdl
Последний рабочий день месяца. Например, Monday[last] это последний понедельник месяца.

y
Год. Предоставляется либо как целое число, либо как целое yearчисло.

ym
Год и месяц.

Возвращаемое значение

1) year_month(y, m)
2) year_month(y, month(m))
3) month_day(m, d)
4) month_day(m, day(d))
5) month_day(month(m), d)
6) month_day(m, d)
7) month_day(month(m), d)
8) month_day_last(m)
9) month_day_last(month(m))
10) month_day_last(m)
11) month_day_last(month(m))
12) month_weekday(m, wdi)
13) month_weekday(month(m), wdi)
14) month_weekday(m, wdi)
15) month_weekday(month(m), wdi)
16) month_weekday_last(m, wdl)
17) month_weekday_last(month(m), wdl)
18) month_weekday_last(m, wdl)
19) month_weekday_last(month(m), wdl)
20) year_month_day(ym.year(), ym.month(), d)
21) year_month_day(ym.year(), ym.month(), day(d))
22) year_month_day(y, md.month(), md.day())
23) year_month_day(year(y), md.month(), md.day())
24) year_month_day(y, md.month(), md.day())
25) year_month_day(year(y), md.month(), md.day())
26) year_month_day_last(ym.year(), month_day_last(ym.month()))
27) year_month_day_last(y, mdl)
28) year_month_day_last(year(y), mdl)
29) year_month_day_last(y, mdl)
30) year_month_day_last(year(y), mdl)
31) year_month_weekday(ym.year(), ym.month(), wdi)
32) year_month_weekday(y, mwd.month(), mwd.weekday_indexed())
33) year_month_weekday(year(y), mwd.month(), mwd.weekday_indexed())
34) year_month_weekday(y, mwd.month(), mwd.weekday_indexed())
35) year_month_weekday(year(y), mwd.month(), mwd.weekday_indexed())
36) year_month_weekday_last(ym.year(), ym.month(), wdl)
37) year_month_weekday_last(y, mwdl.month(), mwdl.weekday_last())
38) year_month_weekday_last(year(y), mwdl.month(), mwdl.weekday_last())
39) year_month_weekday_last(y, mwdl.month(), mwdl.weekday_last())
40) year_month_weekday_last(year(y), mwdl.month(), mwdl.weekday_last())

Пример: operator/ для дат календаря

// compile using: /std:c++latest
#include <iostream>
#include <chrono>

using namespace std::chrono;

int main()
{
    month m{ July }; // Jul
    month_day md{ April / 4 }; // Apr/04
    month_day md2{ 4d / April }; // Apr/04
    month_day_last mdl{ January / last }; // Jan/last
    month_weekday mw{ 11 / Monday[1] }; // Nov/Mon[1]
    month_weekday_last mwl{ January / Monday[last] }; // Jan/Mon[last]
    weekday wd{ Monday }; // Mon
    weekday_indexed wdi{ Monday, 1 }; // Mon[1]
    year_month ym{ 2021y / April }; // 2021/Apr
    year_month_day ymd{ January / 1d / 2021y }; // 2021-01-01
    year_month_day ymd2{ 2021y / 5 / 7 }; // 2021-05-07
    year_month_day_last ymdl{ April / last / 1975 }; // 1975/Apr/last
    year_month_weekday ymw{ 1997y / January / Wednesday[1] }; // 1997/Jan/Wed[1]
    year_month_weekday_last ymwl{ 1997y / January / Wednesday[last] }; // 1997/Jan/Wed[last]
    int yearValue{ 2021 / 4 / 4 }; // 126

    std::cout << m << '\n' << md << '\n' << md2 << '\n' << mdl << '\n' << mw
        << '\n' << mwl << '\n' << wd << '\n' << wdi << '\n'
        << ym << '\n' << ymd << '\n' << ymd2 << '\n' << ymdl
        << '\n' << ymw << '\n' << ymwl << '\n' << yearValue;

    return 0;
}
Jul
Apr/04
Apr/04
Jan/last
Nov/Mon[1]
Jan/Mon[last]
Mon
Mon[1]
2021/Apr
2021-01-01
2021-05-07
1975/Apr/last
1997/Jan/Wed[1]
1997/Jan/Wed[last]
126