Get current timestamp in milliseconds since Epoch in C++
This post will discuss how to get the current timestamp in milliseconds since Epoch in C++.
1. Using std::chrono
Since C++11, we can use std::chrono
to get elapsed time since Epoch. The idea is to get the current system time with std::chrono::system_clock::now()
. Then invoke the time_since_epoch()
function to get the duration representing the amount of time elapsed since Epoch.
The following code example demonstrates its usage. It translates the duration to milliseconds and seconds using std::chrono::duration_cast
. Note that C++20 standardized the time_since_epoch()
function to Unix Epoch.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <chrono> int main() { using namespace std::chrono; uint64_t ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count(); std::cout << ms << " milliseconds since the Epoch\n"; uint64_t sec = duration_cast<seconds>(system_clock::now().time_since_epoch()).count(); std::cout << sec << " seconds since the Epoch\n"; return 0; } |
2. Using std::time
The std::time
returns the current calendar time encoded as a std::time_t
object. It is defined in the header <ctime>
. The following code example demonstrates its usage to get the number of seconds that have passed since the epoch.
1 2 3 4 5 6 7 8 9 10 |
#include <iostream> #include <ctime> int main() { std::time_t ms = std::time(nullptr); std::cout << ms << " seconds since the Epoch\n"; return 0; } |
That’s all about getting the current timestamp in milliseconds since Epoch in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)