c++visual-c++c++20c++-chronoostringstream

How to convert std::chrono::zoned_time to std::string


What is the most efficient way to convert from std::chrono::zoned_time to std::string?

I came up with this simple solution:

#include <iostream>
#include <sstream>
#include <string>
#include <chrono>


#if __cpp_lib_chrono >= 201907L
[[ nodiscard ]] inline auto
retrieve_current_local_time( )
{
    using namespace std::chrono;
    return zoned_time { current_zone( ), system_clock::now( ) };
}
#endif

int main( )
{
    const std::chrono::zoned_time time { retrieve_current_local_time( ) };
    const auto str { ( std::ostringstream { } << time ).str( ) };

    std::cout << str << '\n';
}

As can be seen, time is inserted into the ostringstream object using the operator<< and then a std::string is constructed from its content.

Is there anything better than this in the standard library?

BTW, why doesn't the above program give proper output when executed on Compiler Explorer?


Solution

  • What you have is not bad. You can also use std::format to customize the format of the time stamp. And std::format returns a std::string directly:

    const auto str = std::format("{}", time);
    

    That gives the same format as what you have.

    const auto str = std::format("{:%FT%TZ}", time);
    

    This gives another popular (ISO) format.

    std::format lives in the header <format>.

    Here is the complete documentation for the chrono format flags.