c++ - 针对 musl 和 glibc 将数据/时间转换为 tm/time_point。一般的方法

标签 c++ c++11 glibc musl

我想将字符串数据转换为 struct tm (c) 或 std::chrono::time_point。问题是我想为标准 libc(glibc 和 musl)提供工作解决方案。我有我想要解析的树标准格式。

  1. RFC-1123

    Sun, 06 Nov 1994 08:49:37 GMT

  2. RFC-850

    "Sunday, 06-Nov-94 08:49:37 GMT"

  3. ANSI C 的 asctime 格式

    Sun Nov 6 08:49:37 1994"

有什么办法可以让它发挥作用吗? std::get_time 有一个 bug
strptime 在 glibc 上工作良好(并且快速),但在 musl 上失败。

有什么想法吗?我不想像 get_time 那样使用流。但如果有必要,那很好。 (用GCC5>和c++11标准就可以了)

最佳答案

Howard Hinnant's free, open source, header-only, date/time library可以将这些格式解析为 std::chrono::time_point,即使在有故障的 get_timestrptime 设施的上下文中。不过,它确实需要使用 std::istringstream。这是它的样子:

#include "date.h"
#include <sstream>

std::chrono::system_clock::time_point
parse_RFC_1123(const std::string& s)
{
    std::istringstream in{s};
    std::chrono::system_clock::time_point tp;
    in >> date::parse("%a, %d %b %Y %T %Z", tp);
    return tp;
}

std::chrono::system_clock::time_point
parse_RFC_850(const std::string& s)
{
    std::istringstream in{s};
    std::chrono::system_clock::time_point tp;
    in >> date::parse("%a, %d-%b-%y %T %Z", tp);
    return tp;
}

std::chrono::system_clock::time_point
parse_asctime(const std::string& s)
{
    std::istringstream in{s};
    std::chrono::system_clock::time_point tp;
    in >> date::parse("%a %b %d %T %Y", tp);
    return tp;
}

可以这样练习:

#include <iostream>

int
main()
{
    auto tp = parse_RFC_1123("Sun, 06 Nov 1994 08:49:37 GMT");
    using namespace date;
    std::cout << tp << '\n';
    tp = parse_RFC_850("Sunday, 06-Nov-94 08:49:37 GMT");
    std::cout << tp << '\n';
    tp = parse_asctime("Sun Nov 6 08:49:37 1994");
    std::cout << tp << '\n';
}

和输出:

1994-11-06 08:49:37.000000
1994-11-06 08:49:37.000000
1994-11-06 08:49:37.000000

解析标志 %a%b 通常是区域设置相关的。但是,如果您使用 -DONLY_C_LOCALE=1 编译此库,它将变得与区域设置无关。无论哪种方式,它应该给出相同的结果。但是从实际的角度来看,如果你编译没有 -DONLY_C_LOCALE=1 并且你没有得到上面的结果,你必须向你的 std::提交错误报告库供应商。

如果你用 -DONLY_C_LOCALE=1 编译,但你没有得到上面的结果,请敲响我的笼子,我会在几天内修复它,如果没有小时。

关于c++ - 针对 musl 和 glibc 将数据/时间转换为 tm/time_point。一般的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45745285/

相关文章:

C++11 正则表达式细节

c++ - 在类层次结构上使用 std::is_base_of 和 decltype

c - glibc和相同代码的性能差异

C++ boost::mpl::type 前向声明

c++ - 在 C++ 中,为什么使用或不使用引用作为结果值会得到不同的结果?

c++ - 高效安全的资源管理

linux - "arm-linux-gcc"和 "sim-panalyzer"导致的奇怪错误位于glibc函数 "dl_aux_init"

linux - 安装 g++ 而不更新 glibc

c++ - 有没有办法获取容器模板类型以将其与另一个 value_type 重用?

c++ - 尝试将 vector<int> 推到映射以计算模式