c++ - boost 日期解析 29FEB

标签 c++ boost boost-date-time

日期时间解析存在一些问题,我不知道有什么好的解决方法。

考虑以下代码:

#include <iostream>
#include <string>
#include <boost/date_time/gregorian/gregorian.hpp>

namespace dt = boost::gregorian;

dt::date parse_date(const std::string& msg, const std::string& format)
{
   std::stringstream s(msg);
   dt::date_input_facet * f = new dt::date_input_facet();
   if (format.empty())
   {
      f->set_iso_format();
   }
   else
   {
      f->format(format.c_str());
   }
   std::locale l(std::locale(), f);
   s.imbue(l);
   dt::date result;
   s >> result;
   return result;
}

int main()
{
    const std::string v = "0229";
    auto p = parse_date(v, "%m%d");
    std::cout << p << std::endl;
}

Live example

问题是,日期时间解析器的默认年份是 1400,不是闰年,所以今年没有 2 月 29 日。主要问题当然是为什么默认 1400 年而不是任何闰年,无论如何我需要一些好的解决方法,有什么想法吗?

最佳答案

我认为“为什么”这个问题不是特别相关¹。这就是它的工作方式。关键是您知道是什么阻止您解析它。

我会做下面简单的事情,或者 just write a tiny spirit parser ( int_parser<unsigned char, 10, 2, 2> twice)并构建一个 ptime直接)。

Live On Coliru

#include <iostream>
#include <string>
#include <boost/date_time/gregorian/gregorian.hpp>

namespace dt = boost::gregorian;

dt::date parse_date_mmdd(const std::string &msg) {
    std::stringstream s("2000" + msg);
    dt::date_input_facet *f = new dt::date_input_facet();
    f->format("%Y%m%d");

    std::locale l(std::locale(), f);
    s.imbue(l);
    dt::date result;
    s >> result;

    return result;
}

int main() {
    const std::string v = "0229";
    auto p = parse_date_mmdd(v);
    std::cout << p << std::endl;
}

打印

2000-Feb-29

¹ 答案可能集中在 “没有与 DayOfYear 关联的数据类型” 作为 DayOfMonth 元组(在日期处理库中没有用处)。所以你总是要根据上下文来决定年份。就像您总是必须决定在哪个时区解释 posix 时间一样。或者甚至要使用哪个日历模型。

关于c++ - boost 日期解析 29FEB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34368789/

相关文章:

C++ 非阻塞 ASIO 运行

c++ - 如何创建自定义 boost::posix_time to_string 格式化程序?

c++ - 如何使用 Windows API 列出目录中的文件?

c++ - 调用成员->函数(this);在析构函数中导致段错误

c++ - 从 boost 创建的缓冲区访问数据

c++ - boost 属性树 xml 编写器输出中没有行尾

c++ - 如何在 boost::date_time 中启用纳秒的情况下使用 boost::thread::timed_join?

c++ - 如何将分数纪元时间戳( double )转换为 std::chrono::time_point?

c++ - 检测 CPU 子类型 iPhone

c++ - g++ 链接静态库