【问题标题】:Convert a double to time point using std chrono library使用 std chrono 库将双精度转换为时间点
【发布时间】:2021-10-13 05:35:24
【问题描述】:

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

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;

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

【问题讨论】:

    标签: c++ epoch chrono


    【解决方案1】:

    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 是一个 durationrepdoubleperiodratio&lt;1&gt;

    现在使用一点 C++20 &lt;chrono&gt; 很方便。不用担心,如果你没有 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 转换为基于doubleseconds,然后再转换为基于secondstime_point

    接下来,最好转换为基于整数的time_point 以查找自午夜以来的时间。您的问题使用 microsecondsmilliseconds 在某种程度上可以互换。所以我将假设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&lt;system_clock, milliseconds&gt;

    接下来可以方便地将tp截断为days的精度:

    auto td = floor<days>(tp);
    

    floor 是 C++17 及更高版本的一部分,但 "date/date.h" 将在 C++11/14 中为您提供它。 days 是日精度 durationtd 只是 Unix 纪元以来的天数,类型为 time_point&lt;system_clock, days&gt;

    也可以将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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 2013-03-16
      • 2013-01-08
      • 2015-06-12
      相关资源
      最近更新 更多