如何将std :: chrono :: zoned_time转换为std :: string

发布于 2025-02-10 09:24:53 字数 939 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

聽兲甴掵 2025-02-17 09:24:53

你拥有的还不错。您也可以使用std ::格式自定义时间戳记的格式。和std ::格式直接返回std :: String直接:

const auto str = std::format("{}", time);

提供与您拥有的格式相同的格式。

const auto str = std::format("{:%FT%TZ}", time);

这给出了另一种流行的(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. And std::format returns a std::string directly:

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.

std::format lives in the header <format>.

Here is the complete documentation for the chrono format flags.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文