Unix Timestamp in C++

std::chrono gives type-safe durations. C++20 added real time zone support via std::chrono::zoned_time.

Need to convert one value rather than write code? Use the interactive converter — it handles every unit and time zone without leaving your browser.

Current Unix timestamp

#include <chrono>
#include <iostream>

using namespace std::chrono;

auto now = system_clock::now();
std::cout << duration_cast<seconds>(now.time_since_epoch()).count() << '\n';
std::cout << duration_cast<milliseconds>(now.time_since_epoch()).count() << '\n';

Timestamp to date (C++20)

#include <chrono>
#include <format>

using namespace std::chrono;

sys_seconds ts{seconds{1710050400}};
std::cout << std::format("{:%Y-%m-%d %H:%M:%S}", ts) << '\n';   // UTC

zoned_time zt{"Asia/Kolkata", ts};
std::cout << std::format("{:%Y-%m-%d %H:%M:%S %Z}", zt) << '\n';

Date to timestamp

using namespace std::chrono;

auto day = year{2024}/March/10;
sys_seconds ts = sys_days{day} + hours{6};
std::cout << ts.time_since_epoch().count() << '\n';   // 1710050400

Pre-C++20 fallback

#include <ctime>

std::time_t t = std::time(nullptr);       // seconds
std::tm tm{};
gmtime_r(&t, &tm);                        // thread-safe on POSIX
char buf[32];
std::strftime(buf, sizeof buf, "%Y-%m-%d %H:%M:%S", &tm);

Pitfalls specific to C++

  • std::gmtime and std::localtime return a pointer to shared static storage and are not thread-safe. Use gmtime_r / gmtime_s.
  • std::tm stores year as "years since 1900" and month zero-indexed — two off-by-N traps in one struct.

Rules that apply in every language

  1. Store UTC, display local. Keep the instant in UTC everywhere in your system and convert only at the point a human reads it.
  2. Name the unit in the identifier. expires_at_ms rather than expires_at costs nothing and prevents the single most common timestamp bug.
  3. Never trust a client clock. Stamp anything security-relevant on the server. See the note on clock skew.
  4. Use 64-bit time. Anything still storing seconds in a signed 32-bit field breaks in January 2038 — see the Year 2038 problem.

The same task in other languages

Frequently asked questions

How do I get the current Unix timestamp in C++?

Use the snippet in the "Current Unix timestamp" section above. C++ works in chrono duration natively, so converting to another unit is a multiplication or an integer division away.

How do I convert a Unix timestamp to a date in C++?

The "Timestamp to date" snippet above shows the idiomatic approach, including how to render the result in a specific time zone rather than whatever zone the machine happens to be set to.

Does C++ handle time zones and daylight saving correctly?

Yes, provided you pass an explicit zone rather than relying on the system default. The gotchas listed on this page cover the specific ways C++ makes that easy to get wrong.