gpt4 book ai didi

c++ - 使用 std chrono 库将 double 转换为时间点

转载 作者:行者123 更新时间:2023-12-05 03:39:06 28 4
gpt4 key购买 nike

我有一个代表纪元时间的 double 值,但增加了微秒的精度。所以像这样的数字:

double time_us=1628517578.547;
std::chrono::time_point time(time_us);

上面的代码不起作用,因为我收到以下错误:

 no instance of constructor "time_point" matches the argument list  

我需要进行此转换以获取当天的毫秒数(从昨晚开始经过的毫秒数)。

我打算使用下面的代码来获取所需的毫秒数:

double sysTOH=time.hour*3600+time.min*60+time.sec+time.usec*1e-6;

实现此目标的最佳方法是什么?

最佳答案

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>;

dsdurationrepdouble和一个 periodratio<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)。

首先转换原始 doubledouble基础seconds , 然后到 time_point基于这些 seconds .

接下来最好转换成整数型time_point找到从午夜开始的时间。您的问题使用 microsecondsmilliseconds有点互换。所以我要假设 milliseconds为了一切。改为microseconds如果需要的话。

auto tp = round<milliseconds>(time);

这需要双基time_point并将其转换为基于积分的 time_point这很重要 milliseconds . round用于避免与基于 double 的表示相关的舍入误差。 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是值是milliseconds的数量自 UTC 午夜以来。如果您需要某个时区定义的午夜,那么需要做更多的工作来考虑 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

关于c++ - 使用 std chrono 库将 double 转换为时间点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68713513/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com