How to convert std::chrono::time_point to string

后端 未结 3 1571
闹比i
闹比i 2020-12-09 16:32

How to convert std::chrono::time_point to string? For example: \"201601161125\".

3条回答
  •  自闭症患者
    2020-12-09 16:52

    Code solution

    The following function converts from chrono time_point to string (serialization).

    #include 
    #include 
    #include 
    
    using time_point = std::chrono::system_clock::time_point;
    std::string serializeTimePoint( const time_point& time, const std::string& format)
    {
        std::time_t tt = std::chrono::system_clock::to_time_t(time);
        std::tm tm = *std::gmtime(&tt); //GMT (UTC)
        //std::tm tm = *std::localtime(&tt); //Locale time-zone, usually UTC by default.
        std::stringstream ss;
        ss << std::put_time( &tm, format.c_str() );
        return ss.str();
    }
    
    // example
    int main()
    {
        time_point input = std::chrono::system_clock::now();
        std::cout << serializeTimePoint(input, "UTC: %Y-%m-%d %H:%M:%S") << std::endl;
    
    }
    

    Time zone

    The time_point data-type has no internal representation for the time-zone, in consequence, the time-zone is aggregated by the conversion to std::tm (by the functions gmtime or localtime). It is not recommended to add/substract the time-zone from the input, because you would get an incorrect time-zone displayed with %Z, thus, it is better to set the correct local time (OS dependent) and use localtime().

    Technical vs User-friendly serialization

    For technical usage, hard-coded time format is a good solution. However, to display to users, one should use a locale to retrieve the user preference and show time-stamp in that format.

    C++20

    Since C++20, we have nice serialization and parsing functions for time_point and duration.

    • std::chrono::to_stream
    • std::chrono::format

提交回复
热议问题