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


Full example:

#include <chrono>
#include <iostream>

int main()
    auto timepoint = std::chrono::system_clock::now();
    std::cout << "Microseconds since epoch: " <<
        std::chrono::duration_cast<std::chrono::microseconds>(timepoint.time_since_epoch()).count() << std::endl;

This prints, for example:

Microseconds since epoch: 1690755479946000