Namespaces
Variants

std::chrono:: floor (std::chrono::time_point)

From cppreference.net
定义于头文件 <chrono>
template < class ToDuration, class Clock, class Duration >

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

floor ( const std:: chrono :: time_point < Clock, Duration > & tp ) ;
(C++17 起)

返回可表示为 ToDuration 的最大时间点 t ,该时间点小于或等于 tp

该函数不参与重载决议,除非 ToDuration std::chrono::duration 的特化。

目录

参数

tp - 要向下取整的时间点

返回值

tp 向下取整到下一个时间点,使用类型为 ToDuration 的时长。

可能的实现

namespace detail
{
    template<class> inline constexpr bool is_duration_v = false;
    template<class Rep, class Period> inline constexpr bool is_duration_v<
        std::chrono::duration<Rep, Period>> = true;
}
template<class To, class Clock, class FromDuration,
         class = std::enable_if_t<detail::is_duration_v<To>>>
constexpr std::chrono::time_point<Clock, To>
    floor(const std::chrono::time_point<Clock, FromDuration>& tp)
{
    return std::chrono::time_point<Clock, To>{
        std::chrono::floor<To>(tp.time_since_epoch())};
}

示例

#include <chrono>
#include <iostream>
#include <string>
template<typename TimePoint>
std::string to_string(const TimePoint& time_point)
{
    return std::to_string(time_point.time_since_epoch().count());
}
int main()
{
    using namespace std::literals::chrono_literals;
    using Sec = std::chrono::seconds;
    std::cout << "时间点\t" "转换\t" "向下取整\t" "四舍五入\t" "向上取整\n";
    std::cout << "(毫秒)\t\t"     "(秒)\t"  "(秒)\t"   "(秒)\t"   "(秒)\n";
    for (const auto value_ms : {5432ms, 5678ms})
    {
        std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>
            time_point_ms(value_ms);
        std::cout
            << to_string(time_point_ms) << "\t\t"
            << to_string(std::chrono::time_point_cast<Sec>(time_point_ms)) << '\t'
            << to_string(std::chrono::floor<Sec>(time_point_ms)) << '\t'
            << to_string(std::chrono::round<Sec>(time_point_ms)) << '\t'
            << to_string(std::chrono::ceil<Sec>(time_point_ms)) << '\n';
    }
}

输出:

时间点	转换	向下取整	四舍五入	向上取整
(毫秒)		(秒)	(秒)	(秒)	(秒)
5432		5	5	5	6
5678		5	5	6	6

参见

将时间点转换为同一时钟下具有不同时长的另一个时间点
(函数模板)
将时间点转换为另一个时间点,向上取整
(函数模板)
将时间点转换为另一个时间点,四舍五入到最接近值,取偶舍入
(函数模板)
将时长转换为另一个时长,向下取整
(函数模板)
(C++11) (C++11)
不大于给定值的最近整数
(函数)