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?
What you have is not bad. You can also use
std::formatto customize the format of the time stamp. Andstd::formatreturns astd::stringdirectly:That gives the same format as what you have.
This gives another popular (ISO) format.
std::formatlives in the header<format>.Here is the complete documentation for the chrono format flags.