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

问题描述:

在我正在处理的应用程序中,我收到ISO格式的日期时间(%Y-%m-%dT%H:%M:%SZ) 。如何在Boost中执行严格的解析:: DateTime

我想检查收到的字符串确实是指定的格式。我想尝试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中定义的格式的字符串?

谢谢

+0

将一个正则表达式的工作? –

+0

另请参见https://stackoverflow.com/questions/46474237/c-boost-date-input-facet-seems-to-parse-dates-unexpectedly-with-incorrect-form/46478956#46478956 – sehe

+0

正则表达式就是我所结束的做起来。我的工作环境不允许我自由使用图书馆(需要通过授权管理等来检查......所以很困难),并且strptime似乎是要走的路,但它也是不允许的,因为它不是标准的,每个操作系统:( – Shuny

你能用另一个free, open-source, header-only date/time library吗?

#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 
+0

nitpick:我不会couting outputTime,因为解析失败....我知道这只是一个例子,但是...我会把它放在别的{} – NoSenseEtAl

+1

我也会。但我着重对OP代码进行直译,包括使用相同的变量名称,并包含相同的错误。 –

+1

b29弹孔;) – NoSenseEtAl