std::chrono:: 到处都有很多东西要写,所以我假设:
using namespace std::chrono;
time_point不是具体类型,it is a class template:
template<class Clock, class Duration = typename Clock::duration> class time_point;
这意味着您必须至少提供第一个模板参数,在您的情况下,最好也提供第二个。
您的输入time_ms 的类型为double,表示计数为seconds。因此,首先创建一个与该描述匹配的类型:
using ds = duration<double>;
ds 是一个 duration 与 rep 的 double 和 period 的 ratio<1>。
现在使用一点 C++20 <chrono> 很方便。不用担心,如果你没有 C++20,有一个free, open-source, header-only preview of it that works with C++11/14/17。
sys_time<ds> time{ds{time_ms}};
sys_time 是由"date/date.h" 提供的类型别名:
time_point<system_clock, duration<double>>
即time_point 基于 system_clock 使用您的自定义 duration 类型 ds(双基 seconds)。
首先将原始double 转换为基于double 的seconds,然后再转换为基于seconds 的time_point。
接下来,最好转换为基于整数的time_point 以查找自午夜以来的时间。您的问题使用 microseconds 和 milliseconds 在某种程度上可以互换。所以我将假设milliseconds 处理所有事情。如果需要,请更改为 microseconds。
auto tp = round<milliseconds>(time);
这采用基于双精度的time_point 并将其转换为基于整数的time_point,该milliseconds 计数。 round 用于避免与基于双精度的表示相关的舍入错误。 round 是 C++17 及更高版本的一部分,但 "date/date.h" 将在 C++11/14 中为您提供它。
tp 的类型是time_point<system_clock, milliseconds>。
接下来可以方便地将tp截断为days的精度:
auto td = floor<days>(tp);
floor 是 C++17 及更高版本的一部分,但 "date/date.h" 将在 C++11/14 中为您提供它。 days 是日精度 duration。 td 只是 Unix 纪元以来的天数,类型为 time_point<system_clock, days>。
也可以将td 视为一天开始的时间点。因此,可以从tp 中减去它以获得“一天中的时间”或“自午夜以来的时间”UTC:
auto tod = tp - td;
tod 的类型为milliseconds,该值是自UTC 午夜以来milliseconds 的数量。如果您需要某个时区定义的午夜,则需要做更多的工作来考虑 UTC 偏移量。您的问题在这一点上含糊不清。
把它们放在一起:
#include "date/date.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
double time_ms=1628517578.547;
using ds = duration<double>;
sys_time<ds> time{ds{time_ms}};
auto tp = round<milliseconds>(time);
auto td = floor<days>(tp);
auto tod = tp - td;
std::cout << "tod = " << tod << '\n';
}
输出:
tod = 50378547ms