c++ - 年份超出有效范围 : 1400. ..10000

标签 c++ parsing boost datetime

我正在尝试使用 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”包含上面的日期。我在格式字符串中犯了错误吗?

最佳答案

%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';
}

关于c++ - 年份超出有效范围 : 1400. ..10000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5422317/

相关文章:

c++ - 如何分配引用链的末端?

c++ - 在特定条件下迭代文件夹的文件

java数据结构模拟数据树

c# - 在 .NET C# 中从未知文化解析 double 的最佳方法是什么?

c++ - 在多边形内查找 Boost rtree 元素

c++ - 转换到一个类并从兄弟类调用函数?

C++ 将对象重新解释为字符串并返回

java - 将 JSON 转换为 YAML。将 JSON 解析为 YAML

c++ - 不支持 boost::filesystem::create_symlink

c++ - 使用 clang++/libc++ 删除 Boost libstdc++ 依赖项?