How to convert std::chrono::time_point to seconds since epoch
If you have a std::chrono::time_point such as
example.cpp
std::chrono::time_point<std::chrono::system_clock> timepoint = std::chrono::system_clock::now();You can convert it to seconds since epoch by first casting it to a chrono::duration using
example.cpp
timepoint.time_since_epoch(); // Returns a duration
and then using std::chrono::duration_cast<std::chrono::seconds>(...).count() to convert it to seconds since epoch and getting the number of intervals (= seconds) in between epoch and the time point.
example.cpp
std::chrono::duration_cast<std::chrono::seconds>(timepoint.time_since_epoch()).count()Full example:
main.cpp
#include <chrono>
#include <iostream>
int main()
{
auto timepoint = std::chrono::system_clock::now();
std::cout << "Seconds since epoch: " <<
std::chrono::duration_cast<std::chrono::seconds>(timepoint.time_since_epoch()).count() << std::endl;
}This prints, for example:
output.txt
Seconds since epoch: 1690755234Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow