从64位整数秒计数创建boost :: posix_time :: ptime对象

mat*_*975 5 c++ boost boost-date-time unix-timestamp

我有一个32位的Linux系统,我必须在其中记录带有时间戳的数据,该时间戳是从1901-01-01 00:00:00的纪元开始的UINT32秒偏移.

计算时间戳对我来说没关系,因为我可以使用64位ticks()计数器和ticks_per_second()函数来生成自纪元以来的秒数,如下所示(我只需要二级分辨率)

const ptime ptime_origin(time_from_string("1901-01-01 00:00:00"));
time_duration my_utc = microsec_clock::universal_time() - ptime_origin;
boost::int64_t tick_per_sec = my_utc.ticks_per_second();
boost::int64_t tick_count = my_utc.ticks();
boost::int64_t sec_since_epoch = tick_count/tick_per_sec;
Run Code Online (Sandbox Code Playgroud)

这对我有用,因为我知道作为无符号整数,秒数不会超过最大UINT32值(不管多少年都没有).

我的问题是我的应用程序可以接收包含UINT32值的modbus消息,我必须ioctl使用调用来设置硬件和系统时钟RTC_SET_TIME.此UINT32再次是自我的纪元1901-01-01 00:00:00以来的秒数偏移量.

我现在的问题是我无法使用64位整数创建一个ptime对象 - 对象的ticks一部分time_duration是私有的,我被限制使用long哪个在我的32位系统上只是一个4字节的有符号整数,不足以存储从我的纪元偏离的秒数.

我无法控制时代的价值,所以我真的很难过如何boost::posix_time::ptime从我拥有的数据中创建我所需的对象.我可以通过计算特定时间间隔的硬第二次计数并使用额外的纪元来建立一个允许这种情况的桥来获得一个肮脏的解决方案,但我想知道boost代码中是否有某些内容可以让我完全使用提升日期时间库.我已经阅读了所有可以找到的文档,但是我看不到任何明显的方法.

编辑:我发现这个相关的问题将int64_t转换为time_duration但是接受的答案对我的纪元不起作用

seh*_*ehe 2

您可以以最大允许增量(即std::numeric_limits<long>::max())应用 time_durations ,因为该total_seconds字段限制为long(有符号)。

注意:我的措辞如下,int32_t以便在 64 位平台上编译时它仍然可以正常工作。

这是一个小演示:

#include "boost/date_time.hpp"
#include <iostream>

using namespace boost::gregorian; 
using namespace boost::posix_time;

int main()
{
    uint64_t offset = 113ul*365ul*24ul*60ul*60ul; // 113 years give or take some leap seconds/days etc.?

    static const ptime time_t_epoch(date(1901,1,1)); 
    static const uint32_t max_long = std::numeric_limits<int32_t>::max();
    std::cout << "epoch: " << time_t_epoch << "\n";

    ptime accum = time_t_epoch;
    while (offset > max_long)
    {
        accum  += seconds(max_long);
        offset -= max_long;
        std::cout << "accumulating: " << accum << "\n";
    }

    accum += seconds(offset);
    std::cout << "final: " << accum << "\n";
}
Run Code Online (Sandbox Code Playgroud)

印刷:

epoch: 1901-Jan-01 00:00:00
accumulating: 1969-Jan-19 03:14:07
final: 2013-Dec-04 00:00:00
Run Code Online (Sandbox Code Playgroud)

观看Coliru 直播