Get Unix timestamp with C++

后端 未结 7 610
南旧
南旧 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 
    #include 
    
    int main()
    {
        const auto p1 = std::chrono::system_clock::now();
    
        std::cout << "seconds since epoch: "
                  << std::chrono::duration_cast(
                       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 
    #include 
    
    int main()
    {
        std::time_t result = std::time(nullptr);
        std::cout << std::asctime(std::localtime(&result))
                  << result << " seconds since the Epoch\n";
    }
    

提交回复
热议问题