c++linuxwindowstime

Get seconds since epoch in Linux


Is there cross-platform solution to get seconds since epoch, for windows i use

long long NativesGetTimeInSeconds()
{
    return time (NULL);
}

But how to get on Linux?


Solution

  • You're already using it: std::time(0) (don't forget to #include <ctime>). However, whether std::time actually returns the time since epoch isn't specified in the standard (C11, referenced by the C++ standard):

    7.27.2.4 The time function

    Synopsis

    #include <time.h>
    time_t time(time_t *timer);
    

    Description

    The time function determines the current calendar time. The encoding of the value is unspecified. [emphasis mine]

    For C++, C++11 and later provide time_since_epoch. However, before C++20 the epoch of std::chrono::system_clock was unspecified and therefore possibly non-portable in previous standards.

    Still, on Linux the std::chrono::system_clock will usually use Unix Time even in C++11, C++14 and C++17, so you can use the following code:

    #include <chrono>
    
    // make the decltype slightly easier to the eye
    using seconds_t = std::chrono::seconds;
    
    // return the same type as seconds.count() below does.
    // note: C++14 makes this a lot easier.
    decltype(seconds_t().count()) get_seconds_since_epoch()
    {
        // get the current time
        const auto now     = std::chrono::system_clock::now();
    
        // transform the time into a duration since the epoch
        const auto epoch   = now.time_since_epoch();
    
        // cast the duration into seconds
        const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(epoch);
        
        // return the number of seconds
        return seconds.count();
    }