Search code examples
c++datetimebooststring-conversionboost-date-time

How to parse date/time from a string in C++


How to convert string with template "%d.%m.%Y %H:%M:%S" (for example, 28.05.2013 17:42:00) to boost::posix_time::ptime or something similar?

The following is my non-working code.

boost::posix_time::ptime stringToDateTime(const std::string &text) {
  const std::locale fct
  (   std::locale::classic()
  ,   new boost::gregorian::date_input_facet("%d.%m.%Y %H:%M:%S")
  );
  std::istringstream is(text);
  is.imbue(fct);
  boost::posix_time::ptime date;
  is >> date;
  return date;
}

Solution

  • boost::posix_time::ptime stringToDateTime(const std::string &text) {
      const std::locale fct
      (   std::locale::classic()
      ,   new boost::posix_time::time_input_facet("%d.%m.%Y %H:%M:%S")
      );           //^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - that was an error
      std::istringstream is(text);
      is.imbue(fct);
      boost::posix_time::ptime date;
      is >> date;
      return date;
    }