Shravan40 Shravan40 - 1 year ago 58
C++ Question

How to convert ‘std::chrono::duration<int, std::ratio<2629746l, 1l> >’ to ‘int’ type?

I am using Howard Hinnant's date library, and trying to find the total number of months between two dates.

invalid static_cast from type ‘std::chrono::duration<int, std::ratio<2629746l, 1l> >’ to type ‘int’
int period = static_cast<int>(period_in_months(start_date, end_date));

Here are the functions I am using:

auto period_in_months(year_month_day start_date, year_month_day end_time) {
auto total_months = ((end_time.year() - start_date.year())*12 + (end_time.month() - start_date.month()));
return (total_months--);

double percentage_return(string risk_profile, year_month_day start_date, year_month_day end_date) {
int period = static_cast<int>(period_in_months(start_date, end_date));
// do something

I tried using
chrono::duration_cast<int>(period_in_months(start_date, end_date)
but received the same error.

Answer Source

Here is an article on this subject:

The article starts with more questions:

Do we want the number of "full months"? Or perhaps we should round to the nearest number of integral months? Or do we want a floating-point representation of months which can show fractional months?

Given two year_month_day objects d1 and d2, here is the difference in months truncated towards zero:

(d2.year()/d2.month() - d1.year()/d1.month())

This returns a chrono duration called months.

The above completely ignores the day field of each date. If you want to take the day field into account and round towards nearest:

auto dp1 = sys_days(d1);
auto dp2 = sys_days(d2);
auto delta = round<months>(dp2-dp1);

There's also a way to get the difference in floating point months shown in the article.

Once you have a chrono duration of any precision, with any representation, one can get the value of that representation out with the .count() member function of chrono::duration:

cout << delta.count() << '\n';