Search code examples
c++c++-chrono

unsigned long long to std::chrono::time_point and back


I am very confused about something. Given:

std::time_t tt = std::time(0);
std::chrono::system_clock::time_point tp{seconds{tt} + millseconds{298}};
std::cout << tp.time_since_epoch().count();

prints something like: 16466745672980000 (for example)

How do I rehydrate that number back into a time_point object? I find myself doing kooky things (that I'd rather not show here) and I'd like to ask what the correct way to do the rehydration is.


Solution

  • system_clock::time_point tp{system_clock::duration{16466745672980000}};
    

    The units of system_clock::duration vary from platform to platform. On your platform I'm guessing it is 1/10 of a microsecond.

    For serialization purposes you could document that this is a count of 1/10 microseconds. This could be portably read back in with:

    long long i;
    in >> i;
    using D = std::chrono::duration<long long, std::ratio<1, 10'000'000>>;
    std::chrono::time_point<std::chrono::system_clock, D> tp{D{i}};
    

    If the native system_clock::time_point has precision as fine as D or finer, you can implicitly convert to it:

    system_clock::time_point tp2 = tp;
    

    Otherwise you can opt to truncate to it with a choice of rounding up, down, to nearest, or towards zero. For example:

    system_clock::time_point tp2 = round<system_clock::duration>(tp);