2013-05-28 5 views
-2

Как преобразовать строку с шаблоном "%d.%m.%Y %H:%M:%S" (например, 28.05.2013 17:42:00) в boost::posix_time::ptime или что-то подобное?Как анализировать дату/время из строки в C++

Ниже приведен мой нерабочий код.

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

ответ

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

Существует уродливый способ, которым я не принимать

boost::posix_time::ptime stringToDateTime(const std::string &text) { 
    return boost::posix_time::time_from_string 
    ( text.substr(6, 4) // year 
    + "-" 
    + text.substr(3, 2) // month 
    + "-" 
    + text.substr(0, 2) // day 
    + text.substr(10, 9) // hour,min,sec 
); 
}