Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a uint64_t to a time_point

I have a uint64_t value which represents nanoseconds since epoch. Now I need to convert this to a time_point.

Currently I have this code:

std::chrono::time_point<std::chrono::nanoseconds> uptime(std::chrono::nanoseconds(deviceUptime));

Later I want to print something like Fri Feb 10 15:13:04 2017. For this I wanted to use this code:

std::time_t t = std::chrono::system_clock::to_time_t(uptime);
std::cout << "Device time: " << std::ctime(&t) << std::endl;

But I get an error:

No viable conversion from 'time_point<std::chrono::nanoseconds>' to 'const time_point<std::__1::chrono::system_clock>'

What do I have to do to convert the time_point to a format which ctime can use? Or is there a better approach for this problem?

like image 227
Pascal Avatar asked Mar 10 '23 21:03

Pascal


2 Answers

Try this:

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(uptime_timepoint);

Alternatively:

std::time_t t = uptime / 1000000000;
like image 128
Maxim Egorushkin Avatar answered Mar 20 '23 19:03

Maxim Egorushkin


If you decide you don't want to loose all that subsecond information when printing out, you could use Howard Hinnant's date library (MIT license):

#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);
}

which will output something like:

Fri Feb 10 15:13:04.123456789 2017

date::sys_time<nanoseconds> is just a typedef for:

std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds>
like image 39
Howard Hinnant Avatar answered Mar 20 '23 18:03

Howard Hinnant