我正在尝试使用 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/