Search code examples
c++datetimec++11epoch

Calendar time with nanoseconds resolution to nanoseconds epoch


I'm working with a property c++11 library which had its own implementation of Datetime their implementation can be simplified as a struct that contains the fraction of time up to nanoseconds. a rough example will look like:

    struct custom_time_t {
       unsigned year;
       unsigned month;
       unsigned day;
       unsigned hour;
       .......
       long long nanoseconds;
    }

I want to get the epoch from this custom object but also in nanoseconds resolution - similar to gettimeofday.

Getting the epoch up to seconds is typical using std::chrono and std::tm but how to get the nanoseconds since epoch as well?


Solution

  • The easiest way is to use this preview of the C++20 <chrono> library.

    #include "date/date.h"
    #include <chrono>
    
    std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds>
    to_time_point(custom_time_t const& t)
    {
        using namespace date;
        using namespace std::chrono;
        return sys_days{year(t.year)/t.month/t.day} + hours(t.hour) + ...
                 + nanoseconds{t.nanoseconds};
    }
    

    The return type has the correct value for a system_clock-based time_point. If you extract the value from it with .time_since_epoch().count(), you will get the number of nanoseconds since (or prior to) 1970-01-01 00:00:00.000000000 UTC.

    One could also use auto as the return type in C++14, but I wanted to be clear what the return type was. There is also a type alias for this return type: sys_time<nanoseconds>.