c++ - issue with creating boost date from string -
i have piece of code tries create boost::gregorian::date object string format end getting boost:gregorian::not_a_date_time though string seems fine. code looks this:
boost::gregorian::date getdatefromstring(std::string date_str, std::string format) const { const std::locale loc = std::locale(std::locale::classic(), new boost::gregorian::date_facet(format.c_str())); std::istringstream is(date_str) ; is.imbue(loc); boost::gregorian::date d; >> d; return d; }
to test call
boost::gregorian::date d = getdatefromstring("20161101","%y%m%d") ;
i not_a_date_time returned; instead if following:
boost::gregorian::date d2 = boost::gregorian::date_from_iso_string( "20161101");
i receive proper date object back. need generic function can take variety of date formats. doing wrong here?
you using date_facet
instead of date_input_facet
:
#include <boost/date_time.hpp> #include <boost/date_time/gregorian/gregorian_io.hpp> boost::gregorian::date getdatefromstring(std::string date_str, std::string format) { const std::locale loc = std::locale(std::locale(), new boost::gregorian::date_input_facet(format.c_str())); std::istringstream is(date_str); is.imbue(loc); boost::gregorian::date d; is.exceptions(~std::ios::iostate::_s_goodbit); >> d; return d; } int main() { boost::gregorian::date d = getdatefromstring("20161101","%y%m%d"); std::cout << d; }
note use of exceptions()
see parser thinks wrong if fails parse. don't want enable unless handle exception.
prints
2016-nov-01
Comments
Post a Comment