How to get current timestamp in milliseconds since 1970 just the way Java gets
Solution 1
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()
);
Solution 2
use <sys/time.h>
struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
refer this.
Solution 3
Since C++11 you can use std::chrono
:
- get current system time:
std::chrono::system_clock::now()
- get time since epoch:
.time_since_epoch()
- translate the underlying unit to milliseconds:
duration_cast<milliseconds>(d)
- translate
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;
}
Solution 4
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;
}
Solution 5
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;
}
Related videos on Youtube
Comments
-
AKIWEB almost 2 years
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?
-
Progo over 9 yearsThis returns the seconds since the epoch. Not milliseconds.
-
P1r4nh4 over 9 yearsNice. Add count() at the end of the line to get number of milliseconds in a fundamental type format.
-
Adem over 9 yearsgood solution, also I think it should be gettimeofday(&tp,NULL);
-
arsenal almost 9 yearsWill this be same if we use
steady_clock
instead ofsystem_clock
? Will both the epoch be same? -
Oz. almost 9 years@lining: Both epochs are likely to be the same, but their values could be different.
steady_clock
will always progress forward, it is a true measure of the time since its epoch whilesystem_clock
may be a representation of the logical time since the epoch. For every leap second the two could grow further apart depending on the system's implementation. -
arsenal almost 9 yearsOk, do you know what is the epoch for
steady_clock
as compared tosystem_clock
? To me epoch for thesystem_clock
(on g++/linux) is in fact the system epoch, but for steady_clock it's something else I guess . And also let's say if we usesystem_clock
, is there any disadvantage in leap year? -
Oz. almost 9 yearsAs far as I know, the epoch for each of the clocks is implementation dependent. Convention is for
system_clock
's to be the same as the UNIX epoch, but the spec only says it must be the system-wide real time wall clock. There is no requirement for thesteady_clock
to match reality, only that it only move forward. -
rustyx about 8 yearsFirst of all, this is C, not C++. Secondly, there are problems with gettimeofday, see this for example.
-
schrödinbug over 7 yearsWhat's the advantage of using the c++11 chrono library as opposed to the gettimeofday?
-
Oz. over 7 years@Jason Besides gettimeofday not being available on Windows, the chrono library can give you higher resolution (gtod is limited to microseconds), provides time units in a type-safe way so the compiler can enforce unit conversions, and works with normal arithmetic operators (adding
timeval
structs is annoying). -
Noitidart over 7 years@P1r4nh4 I needed it in
int
but when I use.count
it gives me a negative number. -
Noitidart over 7 yearsI get a negative number
-560549313
this is not right, right? -
kayleeFrye_onDeck over 7 years@Noitidart Can you tell me what platform and C++ compiler you're using? I use this thing all the time with automation tools, and have never seen a negative output o.0 More than happy to check it though. Also, is that a direct copy, or modified/integrated program? Just want to make sure it's originating from this code only.
-
Noitidart over 7 yearsAh @kayleeFrye_onDeck its because I was using
int
!int nowms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
. I swithced that toint64_t
and it works! Thanks so much for asking for more info to help! -
Pototo about 7 yearsHow do I convert this to int64_t?
-
Oz. about 7 years@Pototo as P1r4nh4 stated, call
.count()
. Check out the linked documentation for more information. en.cppreference.com/w/cpp/chrono/duration -
Fantastory over 6 yearsJavascript developers are laughing at me seeing this :(
-
ESPeach about 5 years@Noitidart ,
long int ns = std::chrono::system_clock::now().time_since_epoch().count();
appears to return the result in nanoseconds. To get it as an int, I'm doingint ms = ns / 1000000 - 1550000;
, which messes with the offsets, but I'm just measuring time deltas in my project. -
S.S. Anne about 4 years
unsigned long long
is more portable, and__int64
is only available on MSVC. -
Mariusz Jaskółka almost 4 yearsthere is no
__int64
type in standard C++. One can usestd::int64_t
instead. -
csg almost 4 yearsI suggest to use
unsigned long long
instead ofuint64_t
. -
DragonJawad almost 4 yearsWhy
unsigned long long
instead ofuint64_t
? I have a natural preference for the shorter type to type -
Potion over 3 yearsHow can I convert this epoch ms to a datetime format where I can extract the date and time like 07/27/2020 and 20:37:46.239522 respectively?
-
Oz. over 3 years@Potion See stackoverflow.com/a/58610754/321937