2017-10-09 70 views
3

在我正在處理的應用程序中,我收到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

回答

2

你能用另一個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