【发布时间】:2018-09-04 23:03:06
【问题描述】:
我正在尝试将日期(以std::string 的形式)转换为std::chrono::time_point。为此,我使用 Boost Date Time。
下面,您可以找到一个最小的工作示例。
但是,我不明白为什么在我看来某些无效的输入字符串似乎不会以某种方式引发异常。
我无法弄清楚这里发生了什么。
#include <iostream>
#include <chrono>
#include <sstream>
#include <boost/date_time.hpp>
using Clock = std::chrono::system_clock;
using TimePoint = std::chrono::time_point<Clock>;
TimePoint timePointFromString(const std::string& date, const std::string& format) {
// local takes care of destructing time_input_facet
auto loc = std::locale(std::locale::classic(), new boost::posix_time::time_input_facet(format));
std::stringstream ss{date};
ss.imbue(loc);
boost::posix_time::ptime pt;
ss >> pt;
if (!ss.good()) {
throw std::runtime_error("Cannot parse string");
}
boost::posix_time::ptime time_t_epoch{boost::gregorian::date(1970, 1, 1)};
boost::posix_time::time_duration diff = pt - time_t_epoch;
Clock::duration duration{diff.total_nanoseconds()};
return TimePoint{duration};
}
int main() {
std::string format{"%Y-%m-%d"};
std::vector<std::string> strings {"2018", "2018-", "19700101", "19700103", "19700301"};
for (const auto& s: strings) {
auto tp = timePointFromString(s, format);
std::cout << s << ": " << TimePoint::clock::to_time_t(tp) << std::endl;
}
}
输出:
2018: 1514764800
2018-: 1514764800
19700101: 23587200
19700103: 23587200
terminate called after throwing an instance of 'std::runtime_error'
what(): Cannot parse string
更新:我误解了这段代码,认为它会进行某种模式匹配。事实并非如此(请参阅Öö Tiib 答案和他的答案下方的 cmets)!显然,最好使用 Howard Hinnant 的 date/time 库。
【问题讨论】: