0

I am trying to subtract a number of days from the current time using the date.h library of Howard Hinnant.

auto currentTime()
{
    using namespace std::chrono;
    return date::floor<seconds>(system_clock::now());
}

auto oldDate(date::days daysNum)
{
    using namespace date;
    auto time = currentTime();
    auto sd = floor<days>(time);
    auto time_of_day = time - sd;
    auto ymd = year_month_day{sd} - daysNum;
    if (!ymd.ok())
        ymd = ymd.year()/ymd.month()/last;
    return sys_days{ymd} + time_of_day;
}

int main(){
    oldDate(date::days{10});
    return 0;
}

However, the compiler complains about auto ymd = year_month_day{sd} - daysNum;. The error is:

no match for `operator-` (operand types are `date::year_month_day` and `date::days {aka std::chrono::duration<int, std::ratio<86400l, 1l> >}`)

Could someone kindly help?

afp_2008
  • 1,940
  • 1
  • 19
  • 46

1 Answers1

1

year_month_day is the wrong data structure for days-oriented arithmetic. The reason is that doing so results in gratuitously expensive code (like putting an indexing operator on std::list).

The right data structure is just a time_point. This makes your oldDate function really simple and very efficient:

auto oldDate(date::days daysNum)
{
    return currentTime() - daysNum;
}

If you were doing calendrical arithmetic with months or years, then your original code is the right idea.

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577