在我正在處理的應用程序中,我收到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中定義的格式的字符串?
謝謝
將一個正則表達式的工作? –
另請參見https://stackoverflow.com/questions/46474237/c-boost-date-input-facet-seems-to-parse-dates-unexpectedly-with-incorrect-form/46478956#46478956 – sehe
正則表達式就是我所結束的做起來。我的工作環境不允許我自由使用圖書館(需要通過授權管理等來檢查......所以很困難),並且strptime似乎是要走的路,但它也是不允許的,因爲它不是標準的,每個操作系統:( – Shuny