2012-12-21 35 views
2

我试图使用C++ Boost date_time库将格式为“16:43 2012年12月12日”的字符串加载到日期输入构面为“% H:%M%B%d,%Y“。 接下来,我想从stringstream创建一个Boost ptime对象,以便我可以进行日期/时间数学计算。 我无法得到它的工作 - 下面是代码:如何从日期输入构面创建Boost ptime对象

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

的autoMatchTime包含一个有效的日期/时间值,但autoMatchReplyTime没有。我想知道这应该如何工作,但是如果我必须使用C strptime为ptime构造函数初始化一个struct tm,我可以这样做。我花了很多时间用gdb进行研究,编码和调试,但无法弄清楚。任何帮助将不胜感激。

回答

3

所以...你为什么试图用date_input_facet而不是time_input_facet?以下示例正常工作。

#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

相关问题