gpt4 book ai didi

c++ - 自纪元以来的时间使用boost进行串接

转载 作者:搜寻专家 更新时间:2023-10-31 01:02:42 25 4
gpt4 key购买 nike

auto timeSinceEpoch = boost::chrono::duration_cast<boost::chrono::microseconds>(boost::chrono::steady_clock::now().time_since_epoch()).count();

boost::posix_time::ptime now(boost::gregorian::date(1970, 1, 1), boost::posix_time::microsec(static_cast<std::int64_t>(timeSinceEpoch)));

std::string str = boost::posix_time::to_iso_string(now);

输出:19700114T232422.133653 这是不正确的,我做错了什么?

最佳答案

在某些系统上,steady_clock 的纪元是启动后的纳秒。

用其他时钟你会得到更有用的预期结果:

Live On Coliru

#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/chrono.hpp>
#include <string>
#include <iostream>

int main()
{
boost::posix_time::ptime const time_epoch(boost::gregorian::date(1970, 1, 1));

auto ms = (boost::posix_time::microsec_clock::local_time() - time_epoch).total_microseconds();
std::cout << "microseconds: " << ms << "\n";

boost::posix_time::ptime now = time_epoch + boost::posix_time::microseconds(ms);
std::cout << boost::posix_time::to_iso_string(now);
}

打印

microseconds: 1415115992000000
20141104T154632

关于c++ - 自纪元以来的时间使用boost进行串接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26738609/

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