Get Unix timestamp with C++ Get Unix timestamp with C++ unix unix

Get Unix timestamp with C++


C++20 introduced a guarantee that time_since_epoch is relative to the UNIX epoch, and cppreference.com gives an example that I've distilled to the relevant code, and changed to 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";}


#include<iostream>#include<ctime>int main(){    std::time_t t = std::time(0);  // t is an integer type    std::cout << t << " seconds since 01-Jan-1970\n";    return 0;}


The most common advice is wrong, you can't just rely on time(). That's used for relative timing: ISO C++ doesn't specify that 1970-01-01T00:00Z is time_t(0)

What's worse is that you can't easily figure it out, either. Sure, you can find the calendar date of time_t(0) with gmtime, but what are you going to do if that's 2000-01-01T00:00Z ? How many seconds were there between 1970-01-01T00:00Z and 2000-01-01T00:00Z? It's certainly no multiple of 60, due to leap seconds.