Search code examples
c++c++11timec++-chrono

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?


Solution

  • 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;