How do I parse weeks-in-year with boost::date_time?

685 views Asked by At

I want to parse strings that consist of a 4-digit year and the week number within the year. I've followed the boost date/time IO tutorial, producing a test example like this:

std::string week_format = "%Y-W%W";
boost::date_time::date_input_facet<boost::gregorian::date, char> week_facet =     boost::date_time::date_input_facet<boost::gregorian::date, char>(week_format);

std::stringstream input_ss;
input_ss.imbue(locale(input_ss.getloc(), &week_facet));

std::string input_week = "2004-W34";
input_ss.str(input_week);

boost::gregorian::date input_date;
input_ss >> input_date;

Unfortunately, input_date just prints as "2004-01-01", implying that it just parsed the year. What am I doing wrong? Is %W not available on input? (The documentation doesn't mark it as such.)

1

There are 1 answers

2
HostileFork says dont trust SE On BEST ANSWER

You are correct that the documentation doesn't mark it as such in the "Format Flags" section (no "!" next to it...)

http://www.boost.org/doc/libs/1_35_0/doc/html/date_time/date_time_io.html#date_time.format_flags

But that seems to be an oversight. Because in Boost's format_date_parser.hpp there is no coverage for this case in parse_date...you can look at the switch statement and see that:

http://svn.boost.org/svn/boost/trunk/boost/date_time/format_date_parser.hpp

Despite the absence of any code to do it, even the comments in the source say it handles %W and %U on parse input. What's up with that? :-/

On another note, I believe week_facet needs to be dynamically allocated in your example:

std::string week_format = "%Y-W%W";
boost::date_time::date_input_facet<boost::gregorian::date, char>* week_facet =
    new boost::date_time::date_input_facet<boost::gregorian::date, char>(
        week_format
    );

std::stringstream input_ss;
input_ss.imbue(std::locale(input_ss.getloc(), week_facet));

(Or at least I had to do it that way to keep the example from crashing.)