function template

std::chrono::duration_cast

<chrono>
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
20
21
22
// duration_cast
#include <iostream>
#include <ratio>
#include <chrono>

int main ()
{
  typedef std::chrono::duration<int> seconds_type;
  typedef std::chrono::duration<int,std::milli> milliseconds_type;

  seconds_type s (1);             // 1 second
  milliseconds_type ms = std::chrono::duration_cast<milliseconds_type> (s);

  ms += milliseconds_type(2500);  // 3500 millisecond

  s = std::chrono::duration_cast<seconds_type> (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