Search code examples
c++timeepoch

c++ chrono giving negative epoch time


I'm using this code to get the current time in milliseconds since epoch

std::chrono::milliseconds ms = std::chrono::duration_cast< std::chrono::milliseconds >(
    std::chrono::high_resolution_clock::now().time_since_epoch()
    );
long currTime = (long)ms.count();

The problem is i'm getting a negative number now, and each call to this gives me a negative number closer to 0. It has been working fine for weeks and was working a couple hours ago. I don't think i've done anything that should have affected it, but its possible.

Heres a couple example numbers i'm getting:

First time: -2145295742
Second time: -2145279907
Third time: -2145268209
Last time: -2144900213

my computers clock time is the right date, so why might i be getting negative numbers here?


Solution

  • You are overflowing the long in your code:

    long currTime = (long)ms.count();
    

    The best thing to do is to make sure your data type is large enough (has enough bits) to represent the duration. I'd do

    auto currTime = ms.count();
    

    Or, make sure you use a type of at least 45 bits (as this is guaranteed to be the minimum size for the integer type in milliseconds). I find the auto in this case really useful, as your code will be portable, and the right type always used by currTime, regardless of compiler/platform.