Kaz*_*ade 6 c++ datetime parsing boost
我正在尝试使用boost :: date_time将日期字符串(从Twitter API获取)解析为ptime对象.日期格式的一个示例是:
Thu Mar 24 16:12:42 +0000 2011
Run Code Online (Sandbox Code Playgroud)
不管我做了什么,在尝试解析字符串时,我得到"年份超出有效范围"异常.日期格式对我来说是正确的,这里是代码:
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;
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,"created_string"包含上述日期.我在格式字符串中犯了错误吗?
和%T
都是%q
在线输出格式标志。
为了证明这一点,请将您的格式更改为"%a %b %d %H:%M:%S +0000 %Y"
,您的程序将按描述运行。
至于时区输入,有点复杂,你可能需要先预处理字符串,将+0000更改为posix时区格式。
编辑:例如你可以这样做:
#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';
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3074 次 |
最近记录: |