c++ - 从字符串创建 boost 日期时出现问题

标签 c++ datetime boost

我有一段代码尝试从字符串格式创建 boost::gregorian::date 对象,但最终得到 boost::gregorian::not_a_date_time 即使字符串看起来没问题。 我的代码如下所示:

boost::gregorian::date getDateFromString(std::string date_str, std::string format) const
    {
        const std::locale loc = std::locale(std::locale::classic(), new boost::gregorian::date_facet(format.c_str())); 
        std::istringstream is(date_str) ; 
        is.imbue(loc);
        boost::gregorian::date d; 
        is >> d; 
        return d; 
    }

为了测试这个,我调用

boost::gregorian::date d = getDateFromString("20161101","%Y%m%d") ; 

我得到一个 not_a_date_time 返回; 相反,如果我执行以下操作:

boost::gregorian::date d2 = boost::gregorian::date_from_iso_string( "20161101");

我收到了正确的日期对象。 我需要一个可以采用多种日期格式的通用函数。我在这里做错了什么?

最佳答案

您正在使用date_facet而不是date_input_facet:

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

boost::gregorian::date getDateFromString(std::string date_str, std::string format)
{
    const std::locale loc = std::locale(std::locale(), new boost::gregorian::date_input_facet(format.c_str())); 
    std::istringstream is(date_str); 
    is.imbue(loc);
    boost::gregorian::date d; 
    is.exceptions(~std::ios::iostate::_S_goodbit);
    is >> d; 
    return d; 
}

int main() {
    boost::gregorian::date d = getDateFromString("20161101","%Y%m%d"); 
    std::cout << d;
}

请注意使用 exceptions() 来查看解析器在解析失败时认为错误的地方。您可能不想启用它,除非您也处理异常。

Live On Coliru

打印

2016-Nov-01

关于c++ - 从字符串创建 boost 日期时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40530954/

相关文章:

c++ - 试图理解 boost 队列示例

python - 如何为 python C++ 嵌入构建 boost 示例

c++ - 当我传递纹理坐标 (OpenGL) 时没有任何显示

c++ - 构建libssh时在qt和cmake错误上找不到libssh的功能

mysql - ORDER BY 两列,但不按时间排序?

java - Android 倒计时无法正常工作,数字在 2 个值之间不断闪烁且时区无法正常工作

c++ - 稀疏建模软件编译错误

c++ - 使用 SetWindowsHookEx Hook 键盘消息的问题

javascript - 从日期中提取月份和年份并显示为 MMM-YY

c++ - 使用 Boost Spirit Qi 解析特定字符串