C++ (using <chrono>, C++11 and later)
#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip>
int main() {
// Current time point
auto now = std::chrono::system_clock::now();
// Convert to time_t for calendar representation
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::cout << "Unix timestamp: " << now_c << "\n";
// Human-readable (UTC)
std::cout << "UTC time: "
<< std::put_time(std::gmtime(&now_c), "%Y-%m-%dT%H:%M:%SZ")
<< "\n";
// Human-readable (local time)
std::cout << "Local time: "
<< std::put_time(std::localtime(&now_c), "%Y-%m-%d %H:%M:%S")
<< "\n";
// Milliseconds since epoch
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch()).count();
std::cout << "Milliseconds since epoch: " << ms << "\n";
return 0;
}
C++20 (cleaner, with <chrono> calendar/timezone support)
#include <iostream>
#include <chrono>
int main() {
using namespace std::chrono;
auto now = system_clock::now();
std::cout << "Timestamp: " << now << "\n"; // e.g. 2026-09-01 12:34:56.789012
// Truncate to seconds
auto now_sec = time_point_cast<seconds>(now);
std::cout << "Seconds precision: " << now_sec << "\n";
return 0;
}
(Requires a compiler with full C++20 <chrono> formatting support β GCC 13+/Clang 17+/MSVC are the safest bets; older compilers may need {fmt} as a fallback.)
Notes
localtime/gmtimereturn pointers to internal static buffers β not thread-safe. Uselocaltime_r/gmtime_r(POSIX) orlocaltime_s/gmtime_s(Windows/C11 Annex K) in multithreaded code.- For monotonic timing (measuring durations, not wall-clock time), prefer
CLOCK_MONOTONICin C orstd::chrono::steady_clockin C++ βsystem_clock/CLOCK_REALTIMEcan jump due to NTP sync or manual clock changes.