Search code examples
c++c++-chrono

How to add chrono::year_month_day to chrono::sys_seconds


Am holding duration's in a year_month_day. Is there a simple way to add the year_month_day duration to a time_point like sys_seconds?

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

Solution

  • 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.