如何在Boost::DateTime中强制执行严格的解析

How to enforce strict parsing in Boost::DateTime

本文关键字:强制执行 Boost DateTime      更新时间:2023-10-16

在我正在处理的应用程序中,我收到ISO格式的日期时间(%Y-%m-%dT%H:%m:%SZ)作为输入。

我想检查一下收到的字符串是否确实是指定的格式。我想试试Boost DateTime库,它似乎非常适合这项任务。

然而,我对DateTime解析的行为感到惊讶。我的代码如下:

#include <string>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <sstream>
int main()
{
std::string inputDate = "2017-01-31T02:15:53Z";
std::string expectedFormat = "%Y-%m-%dT%H:%M:%SZ";
boost::posix_time::time_input_facet *timeFacet = new boost::posix_time::time_input_facet(expectedFormat);
std::stringstream datetimeStream(inputDate);
datetimeStream.imbue(std::locale(std::locale::classic(), timeFacet));
boost::posix_time::ptime outputTime;
datetimeStream >> outputTime;
if (datetimeStream.fail())
{
std::cout << "Failure" << std::endl;
}
std::cout << outputTime << std::endl;
return 0;
}

运行此程序时,输出为:

2017-Jan-31 02:15:53

正如预期的那样。但是,如果我将inputDate更改为无效的日期时间,如"2017-01-31T02:15:63Z">(不应接受63秒),则输出将为

2017-Jan-31 02:16:03

而不是"失败"信息。我理解背后的逻辑,但我想强制执行更严格的解析。此外,当使用"2017-01-31T02:15:53Z我喜欢Stackoverflow">作为输入时,解析仍然可以工作,考虑到它不尊重指定的格式,这就更奇怪了。

所以我的问题是:如何强制Boost DateTime拒绝那些不严格遵守time_input_facet中定义的格式的字符串?

感谢

你能使用另一个免费的、开源的、只包含标题的日期/时间库吗?

#include "date/date.h"
#include <iostream>
#include <sstream>
int
main()
{
std::string inputDate = "2017-01-31T02:15:63Z";
std::string expectedFormat = "%Y-%m-%dT%H:%M:%SZ";
std::stringstream datetimeStream{inputDate};
date::sys_seconds outputTime;
datetimeStream >> date::parse(expectedFormat, outputTime);
if (datetimeStream.fail())
{
std::cout << "Failure" << std::endl;
}
using date::operator<<;
std::cout << outputTime << std::endl;
}

输出:

Failure
1970-01-01 00:00:00