How to get current timestamp in milliseconds since 1970 just the way Java gets

AKIWEB picture AKIWEB · Oct 24, 2013 · Viewed 340.1k times · Source

In Java, we can use System.currentTimeMillis() to get the current timestamp in Milliseconds since epoch time which is -

the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

In C++ how to get the same thing?

Currently I am using this to get the current timestamp -

struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds

cout << ms << endl;

This looks right or not?

Answer

Oz. picture Oz. · Oct 24, 2013

If you have access to the C++ 11 libraries, check out the std::chrono library. You can use it to get the milliseconds since the Unix Epoch like this:

#include <chrono>

// ...

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