Search code examples
c++epochc++-chrono

How to find the time difference in milliseconds between an epoch timestamp and std::chrono::system_clock::now


Hi all I have created a c++ app that among others it uses std::chrono in order to calculate time differences.
At some point I upload a file to a server and as a response I get an epoch timestamp from a receive.php that informs about the timestamp when the file is fully uploaded to server. I'd like to calculate a time diff between this epoch time stamp and a starting point of my choice since I should not change this receive.php way of working. So far I tried to achive this by using the following code:

#include <iostream>
#include <chrono>

using namespace std;

int main()
{
auto epoch1 = std::chrono::system_clock::now().time_since_epoch() ;
auto epoch2= std::chrono::duration<long long>(epoch_time_stamp);
auto diff = epoch1 - epoch2 ;
auto s = std::chrono::duration_cast<std::chrono::milliseconds>(diff);
cout << s.count() << endl;
}

Where the epoch_time_stamp is a 13 digit epoch timestamp e.x 1501190040123.
However I get false results. I tried to pass epoch_time_stamp both as int64_t and time_t but with no success.Since I'm quite new at using std::chrono I assume that the cast of epoch2 is not correct.

Any ideas what should I do?


Solution

  • As you probably already know, your epoch_time_stamp is a count of milliseconds since 1970-01-01 00:00:00 UTC. When you say:

    auto epoch2= std::chrono::duration<long long>(epoch_time_stamp);
    

    you are quietly converting that count of milliseconds into a count of seconds. You can convert it to a count of milliseconds with:

    auto epoch2= std::chrono::duration<long long, std::milli>(epoch_time_stamp);
    

    And then I think you will start getting results that look right to you.

    I find it helpful to create a templated using alias like this:

    template <class D>
    using sys_time = std::chrono::time_point<std::chrono::system_clock, D>;
    

    Now sys_time<milliseconds> is a time_point which counts milliseconds since the epoch. This would allow you to simplify your code down to:

    auto remote_time = sys_time<milliseconds>{milliseconds{epoch_time_stamp}};
    cout << duration_cast<milliseconds>(system_clock::now() - remote_time).count() << "ms\n";
    

    For more details about <chrono>, please see this video tutorial.