Get Unix timestamp with C++

2rs2ts picture 2rs2ts · May 16, 2011 · Viewed 201.9k times · Source

How do I get a uint unix timestamp in C++? I've googled a bit and it seems that most methods are looking for more convoluted ways to represent time. Can't I just get it as a uint?

Answer

Tony Delroy picture Tony Delroy · May 16, 2011

C++20 introduced a guarantee that time_since_epoch will be relative to the UNIX epoch, and gives this example (distilled to relevant code, and in units of seconds rather than hours):

#include <iostream>
#include <chrono>

int main()
{
    const auto p1 = std::chrono::system_clock::now();

    std::cout << "seconds since epoch: "
              << std::chrono::duration_cast<std::chrono::seconds>(
                   p1.time_since_epoch()).count() << '\n';
}

Using C++17 or earlier, time() is the simplest function - seconds since Epoch, which for Linux and UNIX at least would be the UNIX epoch. Linux manpage here.

The cppreference page linked above gives this example:

#include <ctime>
#include <iostream>

int main()
{
    std::time_t result = std::time(nullptr);
    std::cout << std::asctime(std::localtime(&result))
              << result << " seconds since the Epoch\n";
}