CKTIS / C++
std::chrono::duration_cast — explicit duration conversion
std::chrono::duration_cast converts a duration to a specified std::chrono::duration type. If scaling requires integer division, the quotient is truncated toward zero after the count is converted to a common intermediate type. The function does not check for overflow.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
std::chrono::duration_cast<ToDuration>(d)The function std::chrono::duration_cast, declared in <chrono>, returns a new duration without changing d. ToDuration must be a specialization of std::chrono::duration, such as std::chrono::seconds, not int. The result is a duration object; use .count() to obtain its unit count.
If the source and destination periods are equal, the function casts the source count directly to the destination representation. Bypassing the common intermediate type can affect which conversions are invoked when a representation is a class type. If the periods differ, the function first converts the source count to a common intermediate type, scales it by the ratio of the source period to the destination period, and then casts the result to the destination representation. Integer division truncates the quotient toward zero, but it operates on the already converted count. If both the intermediate type and the destination representation are unsigned long long, converting -500 milliseconds to seconds first turns -500 into a large unsigned value before division by 1000. The result is a large positive count, not zero. In the example shown, -1750 milliseconds becomes -1 second, not -2. Converting back to milliseconds cannot recover the lost 750 milliseconds.
The duration constructor permits some implicit conversions but blocks, among others, conversion from integral milliseconds to integral seconds. duration_cast explicitly requests such a conversion. It is not a range check: intermediate multiplication can overflow, and signed overflow causes undefined behavior. For floating-to-integral conversion, avoid NaN, infinity, and values whose truncated result is not representable in the destination type—the behavior is then undefined.
Examples
#include <chrono>
#include <iostream>
int main() {
constexpr std::chrono::milliseconds input{-1750};
constexpr auto whole =
std::chrono::duration_cast<std::chrono::seconds>(input);
constexpr auto restored =
std::chrono::duration_cast<std::chrono::milliseconds>(whole);
static_assert(whole.count() == -1);
static_assert(restored.count() == -1000);
std::cout << whole.count() << '\n'
<< restored.count() << '\n';
}
Result
-1 -1000
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.