function template
<chrono>

std::chrono::duration_cast

template <class ToDuration, class Rep, class Period>  constexpr ToDuration duration_cast (const duration<Rep,Period>& dtn);
Duration cast
Converts the value of dtn into some other duration type, taking into account differences in their periods.

The function does not use implicit conversions. Instead, all count values are internally converted into the widest representation (the common_type for the internal count types) and then casted to the destination type, all conversions being done explicitly with static_cast.

If the destination type has less precision, the value is truncated.

Parameters

dtn
A duration object.

Return value

The value of dtn converted into an object of type ToDuration.
ToDuration shall be an instantiation of duration.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// duration_cast
#include <iostream>     // std::cout
#include <chrono>       // std::chrono::seconds, std::chrono::milliseconds
                        // std::chrono::duration_cast

int main ()
{
  std::chrono::seconds s (1);             // 1 second
  std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds> (s);

  ms += std::chrono::milliseconds(2500);  // 2500 millisecond

  s = std::chrono::duration_cast<std::chrono::seconds> (ms);   // truncated

  std::cout << "ms: " << ms.count() << std::endl;
  std::cout << "s: " << s.count() << std::endl;

  return 0;
}

Output:
ms: 3500
s: 3


See also