The UNIX timestamp is an integer that represents the number of seconds elapsed since January 1 1970. The timestamp in JavaScript is expressed in milliseconds.
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()
);
use <sys/time.h>
struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
refer this.
This answer is pretty similar to Oz.'s, using <chrono>
for C++ -- I didn't grab it from Oz. though...
I picked up the original snippet at the bottom of this page, and slightly modified it to be a complete console app. I love using this lil' ol' thing. It's fantastic if you do a lot of scripting and need a reliable tool in Windows to get the epoch in actual milliseconds without resorting to using VB, or some less modern, less reader-friendly code.
#include <chrono>
#include <iostream>
int main() {
unsigned __int64 now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
std::cout << now << std::endl;
return 0;
}
Since C++11 you can use std::chrono
:
std::chrono::system_clock::now()
.time_since_epoch()
duration_cast<milliseconds>(d)
std::chrono::milliseconds
to integer (uint64_t
to avoid overflow)#include <chrono>
#include <cstdint>
#include <iostream>
uint64_t timeSinceEpochMillisec() {
using namespace std::chrono;
return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
int main() {
std::cout << timeSinceEpochMillisec() << std::endl;
return 0;
}
If using gettimeofday you have to cast to long long otherwise you will get overflows and thus not the real number of milliseconds since the epoch: long int msint = tp.tv_sec * 1000 + tp.tv_usec / 1000; will give you a number like 767990892 which is round 8 days after the epoch ;-).
int main(int argc, char* argv[])
{
struct timeval tp;
gettimeofday(&tp, NULL);
long long mslong = (long long) tp.tv_sec * 1000L + tp.tv_usec / 1000; //get current timestamp in milliseconds
std::cout << mslong << std::endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With