Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get boost::posix_time::ptime from formatted string

Tags:

c++

boost

I have a formated string like "2012-03-28T08:00:00". i want to get year, month(in string format),date,hour, min ,sec and day (in string format). can any one suggest me the easiest way to do it in boost.

thanks

like image 998
Dev Avatar asked May 07 '12 14:05

Dev


2 Answers

If the existing from_string() methods do not suit your needs then you can use a time input facet that allows you to customise the format from which the string is parsed.

In your case you can use the ISO extended format string so you can use the following code to parse your strings:

    boost::posix_time::time_input_facet *tif = new boost::posix_time::time_input_facet;
    tif->set_iso_extended_format();
    std::istringstream iss("2012-03-28T08:00:00");
    iss.imbue(std::locale(std::locale::classic(), tif));
    iss >> abs_time;
    std::cout << abs_time << std::endl;
like image 135
tinman Avatar answered Nov 12 '22 11:11

tinman


Without using facets;

ptime dateTime = boost::date_time::parse_delimited_time<ptime>(string, 'T');

The two from*_string functions have limits on what formats are converted.

  • Does not accept 'T': time_from_string(s).
  • Does not accept '-': from_iso_string(s).

Roundtripping ISO 8601 date/time in boost;

std::string date = to_iso_extended_string(dateTime);

like image 44
Trygve Sørdal Avatar answered Nov 12 '22 10:11

Trygve Sørdal