解析错误输入时的c++ boost时间验证

c++ boost time validation when parsing a wrong input

本文关键字:c++ boost 时间 验证 错误 输入      更新时间:2023-10-16

我正在学习C++并制作一个简单的应用程序,并且我有以下代码将std::string解析为ptime:

ptimePointer CsvHelper::string_to_ptime(const std::string& s, const int mode, 
    timePointer pt)
{
    const std::locale formats[] = {
        std::locale(std::locale::classic(),new boost::posix_time::time_input_facet("%d/%m/%Y H:%M:%S")),
        std::locale(std::locale::classic(),new boost::posix_time::time_input_facet("%H:%M"))
    };
    std::istringstream is(s);
    is.imbue(formats[mode]);
    is >> *pt;
}
return pt;

问题是,如果我传递一个字母"a",它将被创建一个具有特殊值"not-a-date-time"的ptime

好的,所以我检查了文档,并了解了如果我用默认构造函数创建ptime,我会得到一个具有相同类型的ptime。因此,在我的代码中,我用以下代码验证了输入:

boost::posix_time::ptime ptime;
if (*this->myDate != ptime)
{
    ...
} else 
{
    treat the problem;
}

我觉得这不是一个明确的解决方案,有什么更好的方法来验证这个日期?

ptime有一个is_not_a_date_time()函数。你可以输入

if(myDate.is_not_a_date_time())
   do_something();