Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse a string with date-time + time offset to a boost::posix_time::ptime?

I have a string "2011-10-20T09:30:10-05:00"

Does someone know how I can parse it with boost::date_time library?

like image 755
Alek86 Avatar asked Dec 09 '11 20:12

Alek86


2 Answers

ok, I've found the answer

the code (for VS)

it converts the string to local_date_time, but for me it's acceptable:

#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;
}

maybe someone will need it

like image 179
Alek86 Avatar answered Nov 19 '22 19:11

Alek86


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))
);

Now t is the UTC time and t_local is the local time.

like image 30
James Brock Avatar answered Nov 19 '22 20:11

James Brock