如何将std :: chrono :: zoned_time转换为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';
}
可以看出,time
is is使用操作员插入
。OSTRINGSTREAM
对象,然后从其内容构建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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你拥有的还不错。您也可以使用
std ::格式
自定义时间戳记的格式。和std ::格式
直接返回std :: String
直接:提供与您拥有的格式相同的格式。
这给出了另一种流行的(ISO)格式。
std ::格式
生活在标题中&lt;格式&gt;
。这是Chrono的完整文档格式标志。
What you have is not bad. You can also use
std::format
to customize the format of the time stamp. Andstd::format
returns astd::string
directly:That gives the same format as what you have.
This gives another popular (ISO) format.
std::format
lives in the header<format>
.Here is the complete documentation for the chrono format flags.