【问题标题】:Convert 32 bit unix timestamp to std::string using std::chrono使用 std::chrono 将 32 位 unix 时间戳转换为 std::string
【发布时间】:2017-06-02 04:19:21
【问题描述】:

我正在尝试使用std::chrono 制作std::string,但遇到了问题。

这是我想模仿的 C(-ish) 代码:

std::uint32_t time_date_stamp = 1484693089;
char date[100];
struct tm *t = gmtime(reinterpret_cast<const time_t*>(&time_date_stamp));
strftime(date, sizeof(date), "%Y-%m-%d %I:%M:%S %p", t);

我的出发点始终是这个std::uint32_t,它来自我无法控制的数据格式。

对不起,我没有任何 C++ 作为起点,我什至不知道如何正确地制作 std::chrono::time_point

【问题讨论】:

标签: c++ c c++11 time chrono


【解决方案1】:

&lt;chrono&gt; 不是用于将日期时间格式化为字符串的库。它对于转换不同的时间表示(毫秒到天等)、将时间戳相加等非常有用。

标准库中唯一的日期时间格式化函数是继承自 C 标准库的函数,包括您已经在“C(-ish)”版本中使用的 std::strftime。编辑:正如 jaggedSpire 所指出的,C++11 引入了std::put_time。它提供了一种便捷的方式来使用与 C 函数使用的 API 相同的 API 来流式传输格式化的日期。

由于std::gmtime(如果你要使用std::localtime)将他们的参数作为unix时间戳,你不需要&lt;chrono&gt;来转换时间。它已经在正确的表示中。只有基础类型必须从std::uint32_t 转换为std::time_t。这在您的 C 版本中没有可移植地实现。

一种转换时间戳的便携方式,基于std::put_time 的格式:

std::uint32_t time_date_stamp = 1484693089;
std::time_t temp = time_date_stamp;
std::tm* t = std::gmtime(&temp);
std::stringstream ss; // or if you're going to print, just input directly into the output stream
ss << std::put_time(t, "%Y-%m-%d %I:%M:%S %p");
std::string output = ss.str();

【讨论】:

    【解决方案2】:

    这是一种简单的方法,无需使用此便携式 C++11/14 free, open-source, header-only library 下降到 C 的 tm

    #include "date.h"
    #include <iostream>
    #include <string>
    
    int
    main()
    {
        std::uint32_t time_date_stamp = 1484693089;
        date::sys_seconds tp{std::chrono::seconds{time_date_stamp}};
        std::string s = date::format("%Y-%m-%d %I:%M:%S %p", tp);
        std::cout << s << '\n';
    }
    

    这个输出:

    2017-01-17 10:44:49 PM
    

    这不存在与古老的gmtime C 函数相关的线程安全问题。

    上面的date::sys_secondstypedefstd::chrono::time_point&lt;std::chrono::system_clock, std::chrono::seconds&gt;

    【讨论】:

    • 我担心只有标题的库date.h 有 8000 行,它包括大约 22 个其他标题(标准 c++ 的东西,但是人......)
    • 当您的供应商发布完整的 C++20 时,date.h 可以替换为 &lt;chrono&gt;sys_seconds 将在命名空间 std::chrono 中,format 将在命名空间 @ 987654335@.
    猜你喜欢
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多