liveBook · Manning

Std::chrono::days

As explained in Learn C++ by Example

std::chrono::days is a C++ chrono duration type representing a 24-hour day.

std::chrono::days is a C++20 chrono duration representing 24-hour day intervals. Use it to report elapsed time in days or connect durations with calendar dates. section 4.2.2 section 4.2.5

Key behavior:

  • Convert a coarser duration to days explicitly with duration_cast<days>. section 4.2.2
  • Expect truncation toward zero when conversion loses precision: 23 hours becomes 0 days. section 4.2.2
  • Convert days back to hours implicitly when the destination is finer-grained. section 4.2.2

Countdown to New Year's Eve

Floor the current time_point to days, construct December 31 from the current year, subtract now from that event, and cast the result to days. section 4.2.5

Listing 4.4 Using duration to move to a coarser representation
void durations()
{
    using namespace std::chrono;
    auto nearly_a_day = hours{23};                      #1
    days a_day = duration_cast<days>(nearly_a_day);     #2
    hours round_trip = a_day;                           #3
    std::cout << nearly_a_day << " cast to " << a_day 
        << " and cast back to " << round_trip << '\n';
}

Shows a complete conversion from 23 hours to days and back, including the resulting precision loss. section 4.2.2

Listing 4.7 Finding how many days there are until the last day of the year
void countdown()
{
    using namespace std::chrono;
    time_point now = system_clock::now();
 
    const auto ymd = year_month_day{
        floor<days>(now)                              #1
    };
 
    auto this_year = ymd.year();                      #2
    auto new_years_eve = this_year / December / 31;   #2
 
    auto event = sys_days(new_years_eve);
    duration dur = event - now;
    std::cout << duration_cast<days>(dur)             #3
               << " until event \n ";
}
 
int main()
{
    countdown();
}

Shows days used with system_clock, year_month_day, sys_days, and duration_cast in a practical countdown. section 4.2.5

How Learn C++ by Example covers it

How deep it goes
Explains duration conversion, precision loss, streaming, and calendar use through worked examples without detailing duration implementation internals.
Examples
Uses a 23-hour conversion, a two-century duration, and a countdown to the last day of the year.
What it assumes
Assumes familiarity with chrono time points and durations while demonstrating day conversion and date construction incrementally.
What you can do after
Apply it via std::chrono to convert durations, inspect day counts, and calculate calendar-based countdowns.
How it connects
Connects std::chrono::duration, duration_cast, time_point, system_clock, year_month_day, and calendars.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.