如何在Boost::DateTime中强制执行严格的解析
How to enforce strict parsing in Boost::DateTime
在我正在处理的应用程序中,我收到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
相关文章:
- 如何对模板类型强制执行常量
- C++:我可以在模板参数包中强制执行至少1个agment吗
- 编译器未强制执行返回协定
- 如何在 Linux 上强制执行矢量下标超出范围的调试断言
- 如何使用C++模板强制执行正式协议?
- 为什么在与静态库链接时强制执行 order(例如 source.cxx -lstatic)
- 当函数在 GCC 中没有任何返回时,如何强制执行错误?
- 执行Boost ASIO队列的最大尺寸
- 强制执行执行顺序
- 替换decorator模式以强制执行创建顺序
- 我可以强制执行标量类型通过 int{} 初始化为零吗?
- 如何在C++17中强制执行模板和模板模板参数之间的约束
- 如何在Boost::DateTime中强制执行严格的解析
- 强制执行C++语句顺序
- makefile是否可以在C++中强制执行依赖项限制
- 强制执行此模板的更好方法
- 为非专用模板实例化强制执行编译错误
- 在编译时强制执行静态存储
- 在代码(C/C++)中强制执行自定义规则
- 执行boost::circular buffer确认自动弹出操作