【问题标题】:How can I use boost::gregorian to parse 2-digit years in C++?如何使用 boost::gregorian 在 C++ 中解析 2 位数年份?
【发布时间】:2012-05-25 21:11:25
【问题描述】:

Boost 中的 boost::gregorian::from_*string() 解析函数似乎只处理 4 位数年份(导致 2 位数年份的运行时错误)。

使用 boost::gregorian::from_*string() 函数处理 2 位数年份的最简洁方法是什么?

一种可能性是结合编程规则对日期字符串进行一些预处理,以添加 2000 或 1900 以清理日期格式,但我不想重新发明轮子并添加太多代码,如果有更好的方法。

【问题讨论】:

    标签: c++ parsing date boost boost-date-time


    【解决方案1】:

    boost 似乎不支持这种格式。幸运的是,解析日期格式是单行的。下面是一个用AXE写的解析器,相信你也可以用Spirit写出类似的代码。

    using namespace boost::gregorian;
    using namespace axe::shortcuts;
    unsigned year, month, day;
    auto date_rule = _uint >> year > '/' > _uint >> month > '/' > _uint >> day > _z;
    std::string date_string("99/01/22");
    if(date_rule(date_string.begin(), date_string.end()).matched)
    {
       date d(year < 100 ? year + 1900 : year, month, day);
       // etc.
    }
    

    【讨论】:

    • 嘿,如果 year 是 2 位数字,那么 year
    【解决方案2】:

    Boost.DateTime 无法做到这一点 - the docs 说有一个 %C 格式标志与您想要的行为相匹配,但它只能用于输出,不能用于输入,即使这样也只能用于有限的集合平台。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多