如何使用 boost::date_time 解析一年中的几周?
我想解析由 4 位数年份和一年中的周数组成的字符串。我遵循了 boost date/time IO 教程,生成了一个如下的测试示例:
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;
不幸的是,input_date
只是打印为“2004-01-01”,这意味着它刚刚解析了年份。我做错了什么? %W
在输入时不可用吗? (文档没有这样标记。)
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是正确的,文档没有在“格式标志”部分中将其标记为这样(旁边没有“!”...)
http://www.boost.org/doc/libs/1_35_0/doc/html/date_time/date_time_io.html#date_time.format_flags
但这似乎是一个疏忽。因为在 Boost 的
format_date_parser.hpp
中,parse_date
中没有覆盖这种情况...您可以查看 switch 语句并看到:http://svn.boost.org/svn/boost/trunk/boost/date_time/format_date_parser.hpp
尽管没有任何代码可以做到这一点,但即使是源代码中的注释也说它在解析输入时处理 %W 和 %U。这是怎么回事? :-/
另一方面,我相信 week_facet 需要在您的示例中动态分配:(
或者至少我必须这样做以防止示例崩溃。)
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 inparse_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:
(Or at least I had to do it that way to keep the example from crashing.)