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?