Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost Date_Time date parsing doesn't work

Tags:

c++

boost

I'm trying to write code to parse date time string using boost 1.55 Date_Time library. But it always produces not-a-date-time date.

boost::gregorian::date d(2005, 6, 25);
boost::gregorian::date d2;
boost::gregorian::date_facet* facet(new boost::gregorian::date_facet("%Y %m %d"));
stringstream ss;
ss.imbue(std::locale(std::cout.getloc(), facet));

ss << d; string s = ss.str(); // s = "2005 06 25"
cout << s << endl;
    stringstream ss2(s);
ss2 >> d2; // not-a-date-time
cout << d2 << endl;

I tried different format specifiers, but it didn't help. I'm using Visual C++ 2013. Is there something wrong with my code?

UPDATE:

My system locale is Russian if that makes any difference.

like image 514
Max Avatar asked Oct 20 '22 09:10

Max


1 Answers

You want to parse so you need the input facet:

See it Live on Coliru

#include <boost/date_time/gregorian/greg_date.hpp>
#include <boost/date_time/gregorian/gregorian_io.hpp>
#include <iostream>

int main()
{
    boost::gregorian::date const d(2005, 6, 25);
    boost::gregorian::date d2;

    std::stringstream oss;
    oss.imbue(std::locale(std::cout.getloc(), new boost::gregorian::date_facet("%Y %m %d")));

    oss << d; 

    oss.imbue(std::locale(std::cout.getloc(), new boost::gregorian::date_input_facet("%Y %m %d")));

    if (oss >> d2)
        std::cout << d2 << std::endl;
    else
        std::cout << "Not parsed\n";
}

Prints

2005-Jun-25

on my machine

like image 97
sehe Avatar answered Oct 23 '22 03:10

sehe