【问题标题】:Year is out of valid range: 1400...10000年份超出有效范围:1400...10000
【发布时间】:2011-03-24 16:22:59
【问题描述】:

我正在尝试使用 boost::date_time 将日期字符串(从 Twitter API 获得)解析为 ptime 对象。日期格式的一个例子是:

Thu Mar 24 16:12:42 +0000 2011

无论我做什么,在尝试解析字符串时都会收到“年份超出有效范围”异常。日期格式对我来说是正确的,这里是代码:

boost::posix_time::ptime created_time;
std::stringstream ss(created_string);
ss.exceptions(std::ios_base::failbit); //Turn on exceptions
ss.imbue(std::locale(ss.getloc(), new boost::posix_time::time_input_facet("%a %b %d %T %q %Y")));
ss >> created_time;

在上面的代码中“created_string”包含上面的日期。是不是格式字符串有误?

【问题讨论】:

  • 可以肯定的是,您在函数调用中使用new 造成了内存泄漏。您对 Java 还是 C# 更有经验?
  • 是的,不用担心,我知道这一点,我一直在重新安排代码试图让它工作,当我得到日期解析时我会修复它:) 编辑:实际上,我认为它不会导致泄漏...除非您将 1 作为第二个可选构造函数 arg 传递,否则会重新计算 time_input_facet。
  • 是的,我刚刚检查过,将指针传递给堆栈上的 time_input_facet 会在语言环境被破坏时导致崩溃(除非您将 1 传递给禁用引用计数的构造函数)。所以上面的代码不会泄漏(即使它看起来应该:))

标签: c++ parsing boost datetime


【解决方案1】:

%T%q 都是输出在线格式标志。

为了证明这一点,将您的格式更改为"%a %b %d %H:%M:%S +0000 %Y",您的程序将按照说明运行。

至于时区输入,有点复杂,可能需要先对字符串进行预处理,将+0000改为posix time zone format

编辑:例如你可以这样做:

#include <iostream>
#include <sstream>
#include <boost/date_time.hpp>
int main()
{
        //std::string created_string = "Thu Mar 24 16:12:42 +0000 2011";
        // write your own function to search and replace +0000 with GMT+00:00
        std::string created_string = "Thu Mar 24 16:12:42 GMT+00:00 2011";

        boost::local_time::local_date_time created_time(boost::local_time::not_a_date_time);
        std::stringstream ss(created_string);
        ss.exceptions(std::ios_base::failbit);
        ss.imbue(std::locale(ss.getloc(),
                 new boost::local_time::local_time_input_facet("%a %b %d %H:%M:%S %ZP %Y")));
        ss >> created_time;
        std::cout << created_time << '\n';
}

【讨论】:

  • 谢谢,通常我会分别尝试使用 %H:%M:%S 和 +0000,但不能同时使用!谢谢!
【解决方案2】:

根据docs%T此时不能用于输入,因为它后面跟着一个!在图表中。我现在无法测试它,但我怀疑这是你的问题。

编辑:

%q 也是一个仅输出标志,如下面的 cmets 中指出的那样。

【讨论】:

  • @Kazade, %q 在描述中也被声明为“仅输出”。我怀疑这是真正的问题。
  • 是的,我也打算对%q 发表评论。它没有漂亮的小! 让它立即显而易见:)
猜你喜欢
  • 2017-09-15
  • 1970-01-01
  • 1970-01-01
  • 2020-03-27
  • 2017-03-28
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多