adding chrono::months to a sys_days

Trying to add 1 month to today does not yield a sys_days!!!

1
2
chrono::sys_days today = getToday();
auto next_month = today + chrono::months{ 1 };


next_month's type is time_point<system_clock, duration<int, ratio<54>>

Why?
Well with VS2022 next_month has type std::chrono::sys_days

What compiler are you using?
I am using VS2022... are you sure?

next_month's type is time_point<system_clock, duration<int, ratio<54>>

can't I cast to duration<days>?
Last edited on
Trying to add 1 month to today does not yield a sys_days!!! [...] next_month's type is time_point<system_clock, duration<int, ratio<54>>
duration<int, ratio<54>> is the type used to represent the sum of n days and m months.

A duration is a count of ticks in units of p/q seconds. For std::chrono::days, the unit p/q is 86400 seconds. 86400 seconds = 1 day. For months it's 2629746 seconds = 1 month.
Those numbers come from the definition of days and months:
1
2
using days = duration<int, std::ratio<86400>>;
using months = duration<int, std::ratio<2629746>>;

Using those numbers the relevant sum is:
n day + m month = n * 86400sec + m * 2629746sec
To evaluate it and store the result in a duration we need to choose just one unit p/q that is known at compile-time.

To do it, the compiler finds gcd(86400, 2629746) = 54 at compile time and factors each term:
54n * 1600sec + 54m * 48699sec = (1600n + 48699m) * 54sec
This says the duration that holds the sum should store (1600n + 48699m) "almost-minutes" where each "almost-minute" is 54 seconds long.

can't I cast to duration<days>?
Since these durations are stored in time_points, use time_point_cast instead:
time_point_cast<days>(next_month);
Last edited on
Trying to add 1 month to today does not yield a sys_days!!!


Well my VS2022 intellisense shows the type of next_month as std::chrono::sys_days!

However typeid shows it as:


class std::chrono::time_point<struct std::chrono::system_clock,class std::chrono::duration<int,struct std::ratio<54,1> > >


so intellisense is again incorrect. AAhhh....
Topic archived. No new replies allowed.