Home > Software design >  C 20 <chrono>: How to calculate difference between year_month_date?
C 20 <chrono>: How to calculate difference between year_month_date?

Time:11-14

Using C 20's <chrono>, how can I find the days difference of two year_month_day objects?

int main()
{
    using namespace std::chrono;
    const auto now = system_clock::now();
    const year_month_day today = floor<days>(now);
    const year_month_day xmas = today.year() / month(12) / day(25);

    const days days_till_xmas = xmas - today;
    // I want something like this ---^
}

CodePudding user response:

You can use std::chrono::sys_days to convert to std::chrono::time_point. For example,

auto diff = std::chrono::sys_days(xmas) - std::chrono::sys_days(today);
std::cout << "diff days: " << std::chrono::duration_cast<std::chrono::days>(diff).count() << "days\n";
  • Related