2

I have tried to use the C++ Boost date_time library to load a string of the format “16:43 December 12, 2012” into a stringstream with a date input facet of “%H:%M %B %d, %Y”. Next I want to create a Boost ptime object from the stringstream so I can do date/time math. I can’t get it to work – below is the code:

std::string autoMatchTimeStr(row["message_time"]);
ptime autoMatchTime(time_from_string(autoMatchTimeStr));

date_input_facet* fin = new date_input_facet("%H:%M %B %d, %Y");
stringstream dtss;

dtss.imbue(std::locale(std::locale::classic(), fin));
dtss << msg.getDate(); //msg.getDate() returns “16:43 December 12, 2012”

ptime autoMatchReplyTime;
dtss >> autoMatchReplyTime;

if( autoMatchReplyTime < autoMatchTime + minutes(15)) {
    stats[ "RespTimeLow" ] = "increment";
    sysLog << "RespTimeLow" << flush;
}

The autoMatchTime contains a valid date/time value but the autoMatchReplyTime does not. I would like to learn how this should work, but if I have to use C strptime to initialize a struct tm for the ptime constructor, I can do that. I’ve spent a lot of time researching, coding, debugging with gdb and can’t figure it out. Any help would be greatly appreciated.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
user1139053
  • 131
  • 3
  • 10

1 Answers1

5

So... Why are you trying to use date_input_facet instead of time_input_facet? Following example works fine.

#include <sstream>
#include <boost/date_time/posix_time/posix_time.hpp>

int main()
{
   const std::string time = "16:43 December 12, 2012";
   boost::posix_time::time_input_facet* facet =
   new boost::posix_time::time_input_facet("%H:%M %B %d, %Y");
   std::stringstream ss;
   ss.imbue(std::locale(std::locale(), facet));
   ss << time;
   boost::posix_time::ptime pt;
   ss >> pt;
   std::cout << pt << std::endl;
}

code

ForEveR
  • 55,233
  • 2
  • 119
  • 133