Dev
Dev

Reputation: 399

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

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

Upvotes: 9

Views: 14972

Answers (2)

Trygve Sørdal
Trygve Sørdal

Reputation: 146

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

Upvotes: 10

tinman
tinman

Reputation: 6608

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;

Upvotes: 11

Related Questions