How to convert std::chrono::time_point to milliseconds since epoch
If you have a std::chrono::time_point
such as
std::chrono::time_point<std::chrono::system_clock> timepoint = std::chrono::system_clock::now();
You can convert it to milliseconds since epoch by first casting it to a chrono::duration
using
timepoint.time_since_epoch(); // Returns a duration
and then using std::chrono::duration_cast<std::chrono::milliseconds>(...).count()
to convert it to milliseconds
since epoch and getting the number of intervals (= seconds) in between epoch and the time point.
std::chrono::duration_cast<std::chrono::milliseconds>(timepoint.time_since_epoch()).count()
Full example:
#include <chrono>
#include <iostream>
int main()
{
auto timepoint = std::chrono::system_clock::now();
std::cout << "Milliseconds since epoch: " <<
std::chrono::duration_cast<std::chrono::milliseconds>(timepoint.time_since_epoch()).count() << std::endl;
}
This prints, for example:
Milliseconds since epoch: 1690755347529