如何解析带有日期时间+时间偏移的字符串到boost :: posix_time :: ptime?

时间:2011-12-09 20:05:49

标签: c++ boost boost-date-time

我有一个字符串“2011-10-20T09:30:10-05:00”

有人知道如何使用boost :: date_time库解析它吗?

2 个答案:

答案 0 :(得分:7)

好的,我找到了答案

代码(对于VS)

它将字符串转换为local_date_time,但对我来说这是可以接受的:

#pragma warning(push)
#pragma warning(disable:4244)
#pragma warning(disable:4245)
#include <boost/date_time/local_time/local_time.hpp>
#pragma warning(pop)

#include <iostream>
#include <string>

int main() 
{
    using namespace std;
    using namespace boost::local_time;

    istringstream ss("2011-10-20T09:30:10-05:00");
    ss.exceptions(ios_base::failbit);
    local_time_input_facet* facet = new local_time_input_facet("%Y-%m-%dT%H:%M:%S%ZP");
    ss.imbue(locale(ss.getloc(), facet));

    local_date_time ldt(not_a_date_time);
    ss >> ldt; // do the parse

    std::cout <<
        ldt.to_string() <<
        "\noffset is: " <<
        to_simple_string(ldt.zone()->base_utc_offset()) <<
        std::endl;
}

也许有人需要它

答案 1 :(得分:2)

const char *s = "2011-10-20T09:30:10-05:00";

boost::posix_time::ptime t_local(
    boost::gregorian::from_string(std::string(s, s + 10)),
    boost::posix_time::duration_from_string(std::string(s + 11, s + 19))
);

boost::posix_time::ptime t(
    t_local - boost::posix_time::duration_from_string(std::string(s + 19, s + 25))
);

现在t是UTC时间,t_local是当地时间。