How do you print a C++11 time_point?

后端 未结 7 1362
执笔经年
执笔经年 2020-12-07 19:47

I\'ve created a time point, but I have been struggling to print it to the terminal.

#include 
#include 

int main(){

    //set         


        
7条回答
  •  难免孤独
    2020-12-07 20:41

    Yet another snippet of code. Plus side is that it is fairly standalone and supports microsecond text representation.

    std::ostream& operator<<(std::ostream& stream, const std::chrono::system_clock::time_point& point)
    {
        auto time = std::chrono::system_clock::to_time_t(point);
        std::tm* tm = std::localtime(&time);
        char buffer[26];
        std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S.", tm);
        stream << buffer;
        auto duration = point.time_since_epoch();
        auto seconds = std::chrono::duration_cast(duration);
        auto remaining = std::chrono::duration_cast(duration - seconds);
        // remove microsecond cast line if you would like a higher resolution sub second time representation, then just stream remaining.count()
        auto micro = std::chrono::duration_cast(remaining);
        return stream << micro.count();
    }
    

提交回复
热议问题