Get Unix timestamp with C++

后端 未结 7 555
南旧
南旧 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:23

    I created a global define with more information:

    #include 
    #include 
    #include 
    
    #define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__)    // only show filename and not it's path (less clutter)
    #define INFO std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [INFO] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
    #define ERROR std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [ERROR] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
    
    static std::time_t time_now = std::time(nullptr);
    

    Use it like this:

    INFO << "Hello world" << std::endl;
    ERROR << "Goodbye world" << std::endl;
    

    Sample output:

    16-06-23 21:33:19 [INFO] main.cpp(main:6) >> Hello world
    16-06-23 21:33:19 [ERROR] main.cpp(main:7) >> Goodbye world
    

    Put these lines in your header file. I find this very useful for debugging, etc.

提交回复
热议问题