[英]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
?从
std::chrono::zoned_time
转换为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.可以看出,使用
operator<<
将time
插入到ostringstream
对象中,然后从其内容构造一个std::string
。
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?顺便说一句,为什么上面的程序在 Compiler Explorer 上执行时没有给出正确的输出?
What you have is not bad.你所拥有的还不错。 You can also use
std::format
to customize the format of the time stamp.您还可以使用
std::format
自定义时间戳的格式。 And std::format
returns a std::string
directly:而
std::format
直接返回一个std::string
:
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.这提供了另一种流行的 (ISO) 格式。
std::format
lives in the header <format>
. std::format
位于标头<format>
中。
Here is the complete documentation for the chrono format flags.这是 chrono 格式标志的完整文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.