繁体   English   中英

std::chrono::system_clock::now() 序列化

[英]std::chrono::system_clock::now() serialization

我如何序列化 std::chrono::system_clock::now() 的结果,以便我可以加载它并将它与以后的时间戳进行比较?

我尝试以下列方式序列化:

std::to_string((uint64_t)std::chrono::system_clock::now().time_since_epoch().count())

然后反序列化它:

std::chrono::milliseconds t(<uint64 number>);
std::chrono::time_point<std::chrono::system_clock>(t); 

反序列化不起作用,object 是 1970 年的第一天

最小示例:

#include <iostream>
#include <chrono>

using namespace std;


static std::string clockToStr(std::chrono::system_clock::time_point timestamp)
{
    static char buffer[64];

    std::time_t t  = std::chrono::system_clock::to_time_t(timestamp);

    ::ctime_r(&t, buffer);
    return std::string(buffer);

}

    int main()
    {
        
        uint64_t t1 = std::chrono::system_clock::now().time_since_epoch().count();
        
        std::chrono::milliseconds t(t1);
        
        auto t2 = std::chrono::time_point<std::chrono::system_clock>(t); 
        
        std::cout<<clockToStr(t2)<<std::endl;
    
        return 0;
    }

如前所述, time_since_epoch不一定以毫秒为单位。 如果要序列化毫秒,请使用duration_cast 否则这样的事情应该有效:

  using clock_t = std::chrono::system_clock;
  clock_t::time_point tp = clock_t::now();
  std::string serialized = std::to_string(tp.time_since_epoch().count());
  clock_t::time_point tp1(clock_t::duration(std::stoll(serialized)));

我们使用使用持续时间的time_point构造函数,这与time_since_epoch()方法相反。

序列化有点不稳定,因为我使用long long 更好的方法是检测clock_t::duration::rep的类型。 像这样:

std::ostringstream os;
os << tp.time_since_epoch().count();
std::string serialized = os.str();
std::istringstream is(serialized);
clock_t::rep count;
is >> count;
clock_t::time_point tp1{clock_t::duration{count}};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM