c++ - 如何使用 boost::date_time 解析一年中的几周?

标签 c++ datetime boost 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 不可用吗? (文档没有这样标记。)

最佳答案

你是正确的,文档没有在“格式标志”部分中将其标记为这样(没有“!”旁边......)

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 需要在您的示例中动态分配:

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));

(或者至少我必须这样做以防止示例崩溃。)

关于c++ - 如何使用 boost::date_time 解析一年中的几周?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7960801/

相关文章:

c++ - 逐字逐句阅读长文本

c++ - 对象的变量类型

javascript - 在 javascript/typescript 中向 Date 添加天数会给出完全错误的日期

php - 如何使用 Doctrine2 将 MySQL 列 "timestamp"映射到一个字段

c# - 将日期和时间字符串序列化为 DateTime 对象

c++ - 如何使用模板函数作为 Boost::Unit-test 的自定义谓词

c++ - QPixmaps 中的 QCursor 重建是否会泄漏内存?

c++ - 在类对象上 boost shared_ptr

c++ - 在 MSVC 11 中 boost "destructor is not virtual"错误

c++ - 如何避免显示浮点: -0. 0