Namespaces
Variants
Views
Actions

std::chrono::time_point_cast

From cppreference.com
< cpp‎ | chrono‎ | time point
 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)

(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)

Elementary string conversions
(C++17)
(C++17)

Stacktrace
 
 
 
Defined in header <chrono>
template <class ToDuration, class Clock, class Duration>

std::chrono::time_point<Clock, ToDuration>

    time_point_cast(const std::chrono::time_point<Clock, Duration> &t);
(since C++11)
(until C++14)
template <class ToDuration, class Clock, class Duration>

constexpr std::chrono::time_point<Clock, ToDuration>

    time_point_cast(const std::chrono::time_point<Clock, Duration> &t);
(since C++14)

Converts a std::chrono::time_point from one duration to another.

time_point_cast participates in overload resolution only if ToDuration is an specialization of std::chrono::duration.

Contents

[edit] Parameters

t - time_point to convert from

[edit] Return value

std::chrono::time_point<Clock, ToDuration>(
    std::chrono::duration_cast<ToDuration>(t.time_since_epoch()))
.

[edit] Example

#include <iostream>
#include <chrono>
 
using Clock = std::chrono::high_resolution_clock;
using Ms = std::chrono::milliseconds;
using Sec = std::chrono::seconds;
 
template<class Duration>
using TimePoint = std::chrono::time_point<Clock, Duration>;
 
inline void print_ms(const TimePoint<Ms>& time_point) 
{
    std::cout << time_point.time_since_epoch().count() << " ms\n";
}
 
int main() 
{
    TimePoint<Sec> time_point_sec(Sec(4));
 
    // implicit cast, no precision loss
    TimePoint<Ms> time_point_ms(time_point_sec);
    print_ms(time_point_ms); // 4000 ms
 
    time_point_ms = TimePoint<Ms>(Ms(5756));
 
    // explicit cast, need when precision loss may happens
    // 5756 truncated to 5000
    time_point_sec = std::chrono::time_point_cast<Sec>(time_point_ms);
    print_ms(time_point_sec); // 5000 ms
}

Output:

4000 ms
5000 ms

[edit] See also

a point in time
(class template) [edit]
converts a time_point to another, rounding down
(function template) [edit]
converts a time_point to another, rounding up
(function template) [edit]
converts a time_point to another, rounding to nearest, ties to even
(function template) [edit]
converts a duration to another, with a different tick interval
(function template) [edit]