首页 > 解决方案 > 如何将 chrono::year_month_day 添加到 chrono::sys_seconds

问题描述

我持有年月日的持续时间。有没有一种简单的方法可以将 year_month_day 持续时间添加到像 sys_seconds 这样的 time_point?

sys_seconds date1 = {};
sys_seconds dat2 = {};
year_month_day calDuration;
date1 = date2 + calDuration;    //error: no match for ‘operator+’ 

标签: c++chrono

解决方案


This is chrono catching logic bugs for you at compile-time. Adding date2 + calDuration is akin to adding tomorrow + today. It just doesn't make sense. And that's why it is a compile-time error.

What you may mean is that you have durations years, months and days. This is not the same as the similarly named types year, month and day. The plural forms are chrono::durations, just like minutes and nanoseconds. days is 24h. And years and months are the average length of those units in the civil calendar.

Conversely, the singular forms year, month and day are the calendrical components that give a name to a day in the civil calendar, e.g. 2020y, December, and 18d. And it is these singular forms that make up a year_month_day, e.g. 2020y/December/18d.

See this SO answer for a deep-dive on the difference between month and months.

There are multiple ways to add the units years and months to a time_point. See this SO answer for a deep-dive on that topic.


推荐阅读