liveBook · Manning

Duration_cast

As explained in Learn C++ by Example

duration_cast is a C++ chrono conversion function template that explicitly converts one duration type to another, truncating when the target period cannot represent the full precision.

duration_cast is a C++ chrono conversion function template for explicitly converting one duration type to another. Use it when the target period cannot represent the source duration exactly; the conversion then truncates toward zero. section 4.2.2 section 4.5

Use duration_cast to make potentially lossy duration conversions visible:

  • Convert a finer duration to a coarser one, such as hours to days. section 4.2.2
  • Expect truncation rather than rounding: 23 hours becomes 0 days, and converting that result back gives 0 hours. section 4.2.2
  • Prefer direct assignment when the conversion cannot lose precision; reserve duration_cast for conversions where loss should be explicit. section 4.2.2 section 4.5

Counting days until payday

After finding an event date, subtract the current time to obtain a duration, then write duration_cast<days>(dur) to report whole days remaining. The output deliberately rounds down by discarding fractional days. section 4.2.6 section 4.3.2

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';
}

A complete example shows the conversion from 23 hours to days, the lossy result, and the loss-preserving-looking round trip back to hours. section 4.2.2

How Learn C++ by Example covers it

How deep it goes
Explains syntax, implicit-conversion boundaries, truncation behavior, and countdown usage without examining implementation internals.
Examples
Demonstrates 23 hours cast to days, custom centuries cast to days, and days-until-payday countdowns.
What it assumes
Builds from chrono durations, their periods, time points, and the distinction between implicit and explicit conversion.
What you can do after
Apply it via std::chrono to convert durations and recognize when truncation makes a result intentionally approximate.
How it connects
Connects duration_cast with chrono durations, time points, system_clock, date arithmetic, and duration formatting.

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.