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
