Get Unix timestamp with C++

后端 未结 7 563
南旧
南旧 2020-12-02 20:00

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 j

相关标签:
7条回答
  • 2020-12-02 20:27

    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";
    }
    
    0 讨论(0)
提交回复
热议问题