Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++-chrono

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.

like image 740
ForeverLearning Avatar asked Sep 01 '25 16:09

ForeverLearning


1 Answers

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);
like image 97
Howard Hinnant Avatar answered Sep 10 '25 09:09

Howard Hinnant