Epoch in C++

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in C++.

#include <iostream>
#include <chrono>
#include <ctime>

int main() {
    // Use std::chrono::system_clock::now() to get the current time
    auto now = std::chrono::system_clock::now();
    std::cout << std::chrono::system_clock::to_time_t(now) << std::endl;

    // Get elapsed time since the Unix epoch in seconds, milliseconds, or nanoseconds
    auto epoch = now.time_since_epoch();
    auto seconds = std::chrono::duration_cast<std::chrono::seconds>(epoch);
    auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(epoch);
    auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(epoch);

    std::cout << seconds.count() << std::endl;
    std::cout << milliseconds.count() << std::endl;
    std::cout << nanoseconds.count() << std::endl;

    // You can also convert integer seconds or nanoseconds since the epoch into the corresponding time
    std::time_t time_seconds = seconds.count();
    std::cout << std::ctime(&time_seconds);

    auto time_point = std::chrono::system_clock::time_point(nanoseconds);
    std::time_t time_nanoseconds = std::chrono::system_clock::to_time_t(time_point);
    std::cout << std::ctime(&time_nanoseconds);

    return 0;
}

To compile and run the program:

$ g++ -std=c++11 epoch.cpp -o epoch
$ ./epoch
1651234567
1651234567
1651234567000
1651234567000000000
Fri Apr 29 12:34:27 2022
Fri Apr 29 12:34:27 2022

In C++, we use the <chrono> library to work with time-related functions. The std::chrono::system_clock::now() function is used to get the current time. We can then use various duration casts to convert the time to seconds, milliseconds, or nanoseconds since the Unix epoch.

The std::time_t type and std::ctime() function are used to convert between time representations and string formats.

Next, we’ll look at another time-related task: time parsing and formatting.