grunk
grunk

Reputation: 14938

Parsing string to boost::posix_time::ptime with milliseconds

I have a set of function that allow me to convert ptime to string and string to ptime according to a specific format. This work well until i need to use millisecond modifier (%f).

The conversion to String is working fine :

std::string strFormat = "%Y-%m-%d %H:%M:%S.%f";
ptime now = microsec_clock::universal_time();
auto str = ToString(strFormat, now);

Will output : 2020-08-26 12:27:54.938943

But the opposite :

auto pt = FromString(strFormat, str);
std::cout << to_simple_string(pt) << std::endl;

Will output : not-a-date-time

The FromString function use time_input_facet :

boost::posix_time::ptime ptime;
boost::posix_time::time_input_facet* infacet = new boost::posix_time::time_input_facet(informat.c_str());

std::stringstream ss;
ss.imbue(std::locale(ss.getloc(), infacet));

ss.str(time);
ss >> ptime;

return ptime;

As you can see Live On Coliru removing the %f modifier is working fine.

What am i missing ? I have tried different format without success. Using boost 1.70

Edit : As specified by @sugar in comments , using %F instead of %f seems to works both ways. Does %f just shouldn't be used ?

Upvotes: 2

Views: 677

Answers (1)

grunk
grunk

Reputation: 14938

It turns out this is a bug on Boost date_time library (issue)

To get around it i simply replace all occurence of ".%f" by "%F" :

boost::posix_time::ptime FromString(std::string informat, std::string time)
            {
                boost::replace_all(informat, ".%f", "%F"); // Get around #102
                boost::posix_time::ptime ptime;
                boost::posix_time::time_input_facet* infacet = new boost::posix_time::time_input_facet(informat.c_str());

                std::stringstream ss;
                ss.imbue(std::locale(ss.getloc(), infacet));

                ss.str(time);
                ss >> ptime;
    
                return ptime;
            }

Upvotes: 2

Related Questions