我有一个uint64_t
值,表示自纪元以来的纳秒数。现在我需要将其转换为time_point
。
目前我有这段代码:
std::chrono::time_point<std::chrono::nanoseconds> uptime(std::chrono::nanoseconds(deviceUptime));
后来我想打印像Fri Feb 10 15:13:04 2017
这样的东西。为此我想使用这段代码:
std::time_t t = std::chrono::system_clock::to_time_t(uptime);
std::cout << "Device time: " << std::ctime(&t) << std::endl;
但是我收到了一个错误:
No viable conversion from 'time_point<std::chrono::nanoseconds>' to 'const time_point<std::__1::chrono::system_clock>'
如何将time_point
转换为ctime
可以使用的格式,我该怎么做?或者有更好的方法解决这个问题吗?
答案 0 :(得分:2)
试试这个:
uint64_t uptime = 0;
using time_point = std::chrono::system_clock::time_point;
time_point uptime_timepoint{std::chrono::duration_cast<time_point::duration>(std::chrono::nanoseconds(uptime))};
std::time_t t = std::chrono::system_clock::to_time_t(timepoint_uptime);
可替换地:
std::time_t t = uptime / 1000000000;
答案 1 :(得分:2)
如果您决定在打印时不想丢失所有亚秒级信息,可以使用Howard Hinnant's date library(MIT许可证):
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
uint64_t deviceUptime = 1486739584123456789;
sys_time<nanoseconds> uptime{nanoseconds(deviceUptime)};
std::cout << format("%a %b %e %T %Y\n", uptime);
}
将输出如下内容:
Fri Feb 10 15:13:04.123456789 2017
date::sys_time<nanoseconds>
仅适用于typedef
:
std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds>