[英]How to convert std::chrono::zoned_time to std::string
从std::chrono::zoned_time
转换为std::string
的最有效方法是什么?
我想出了这个简单的解决方案:
#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';
}
可以看出,使用operator<<
将time
插入到ostringstream
对象中,然后从其内容构造一个std::string
。
标准库中还有什么比这更好的吗?
顺便说一句,为什么上面的程序在 Compiler Explorer 上执行时没有给出正确的输出?
你所拥有的还不错。 您还可以使用std::format
自定义时间戳的格式。 而std::format
直接返回一个std::string
:
const auto str = std::format("{}", time);
这给出了与你所拥有的相同的格式。
const auto str = std::format("{:%FT%TZ}", time);
这提供了另一种流行的 (ISO) 格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.