How to convert std::chrono::time_point to seconds 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 seconds 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::seconds>(...).count() to convert it to seconds since epoch and getting the number of intervals (= seconds) in between epoch and the time point.


Full example:

#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:

Seconds since epoch: 1690755234