hg_git hg_git - 10 months ago 39
C++ Question

portable way to store milliseconds with chrono

I've a code as follows -

int main(){
....

auto time = std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1);

....
return 0;
}


The variable
time
here gives output as
l
with
typeid().name()
method, but is it safe to assume that if I replace auto with
long
type, the variable will still store the correct amount of milliseconds across different machines?

I need it because I cannot specify
auto
as type in class members, since they aren't constexpr or static where it might've been possible. And my intent is to send the data to browser where I can do
var d = new Date(time)
and it displays correct time. The communication part has been figured out via json format, I'm only stuck at how to store it correctly across different systems.

Answer Source

[...] is it safe to assume that if I replace auto with long type, the variable will still store the correct amount of milliseconds across different machines?

No, you need a signed integer type of at least 45 bits, which long is not guarantee to be. You should use std::chrono::milliseconds::rep:

using namespace std::chrono;
milliseconds::rep time = 
    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();

Also note that in term of portability, the system_clock's epoch is not guaranteed to be January 1st 1970 00:00:00 UTC by the standard (even if it is the cast most of the time).