Epoch & Unix Timestamp in C++

Get the current epoch timestamp

#include <chrono>

auto epoch_seconds = std::chrono::duration_cast<std::chrono::seconds>(
    std::chrono::system_clock::now().time_since_epoch()).count();

Convert epoch to date

#include <chrono>
// C++20
std::chrono::sys_seconds tp{std::chrono::seconds{1718200000}};
auto str = std::format("{:%Y-%m-%d %H:%M:%S}", tp);

Convert date to epoch

#include <chrono>
using namespace std::chrono;
// C++20
auto epoch = sys_days{year{2026}/6/12}.time_since_epoch().count() * 86400;

C++ notes

Since C++20, system_clock is guaranteed to be Unix time. Pre-C++20, drop to the C functions for calendar conversion or use Howard Hinnant's date library.

Check any value live with the epoch converter, or read what Unix time actually counts.

Other languages

C · C# · Dart · Go · Java · JavaScript · Kotlin · MySQL · Perl · PHP · PostgreSQL · Python · R · Ruby · Rust · Scala · SQLite · Swift · TypeScript