Current epoch — epochtime.tools · A precision instrument for time

Get the current Unix timestamp

/* C */
#include <time.h>
time_t s = time(NULL);
struct timespec ts;
timespec_get(&ts, TIME_UTC);          /* C11: ts.tv_sec + ts.tv_nsec */

// C++
#include <chrono>
using namespace std::chrono;
auto s2 = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
auto ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();

Convert a Unix timestamp to a date

/* C: epoch to UTC text */
time_t t = 1700000000;
struct tm tm;
gmtime_r(&t, &tm);                    /* POSIX; gmtime_s on Windows */
char buf[32];
strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", &tm);   /* 2023-11-14T22:13:20Z */

// C++20
#include <format>
std::chrono::sys_seconds tp{std::chrono::seconds{1700000000}};
std::string s = std::format("{:%F %T}", tp);            // "2023-11-14 22:13:20"

Convert a date to a Unix timestamp

/* C: UTC calendar time to epoch. timegm is not ISO C, but glibc, musl and the BSDs have it */
struct tm tm = {0};
tm.tm_year = 2026 - 1900; tm.tm_mon = 10; tm.tm_mday = 14; tm.tm_hour = 10;
time_t t = timegm(&tm);               /* 1794650400; _mkgmtime on Windows */

// C++20
using namespace std::chrono;
auto tp = sys_days{2026y / November / 14} + 10h;
auto s = duration_cast<seconds>(tp.time_since_epoch()).count();   // 1794650400

Timezones

// C++20 time zones (libstdc++ 13+, MSVC 2019 16.10+)
#include <chrono>
#include <format>
using namespace std::chrono;
zoned_time z{"Asia/Kolkata", sys_seconds{seconds{1700000000}}};
std::string s = std::format("{:%F %T %Z}", z);   // "2023-11-15 03:43:20 IST"

Common mistakes

  • mktime() reads the struct as local time. Use timegm() or C++20 sys_days for UTC.
  • A 32-bit time_t overflows on 19 January 2038. Check sizeof(time_t) on embedded targets. See Year 2038 Year 2038 checker Unix time 2 billion.
  • gmtime() and localtime() return a pointer to shared static storage. Use gmtime_r/localtime_r in threaded code.
  • Before C++20, system_clock's epoch was unspecified, though every major library used 1970.

Complete example

#include <chrono>
#include <format>
#include <iostream>

int main() {
    using namespace std::chrono;
    auto now = floor<seconds>(system_clock::now());
    std::cout << "Now: " << now.time_since_epoch().count() << '\n';
    sys_seconds t{seconds{1700000000}};
    std::cout << std::format("UTC: {:%FT%TZ}", t) << '\n';
}

Check any value with the epoch converter, or convert a whole column with the batch converter. All examples use 1700000000 (2023-11-14 22:13:20 UTC) and 1794650400 (2026-11-14 10:00:00 UTC).

Official documentation

Last updated: