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

SyntaxFix
Jun 1, 2022

--

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?

Best Solutions is

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()

--

--

SyntaxFix

Curated Solutions On Popular Questions — On All Programming Languages, Cloud Computing, Tools etc