Drew Noakes Drew Noakes - 9 months ago 98
C++ Question

How to parse a date string into a c++11 std::chrono time_point or similar?

Consider a historic date string of format:

Thu Jan 9 12:35:34 2014

I want to parse such a string into some kind of C++ date representation, then calculate the amount of time that has passed since then.

From the resulting duration I need access to the numbers of seconds, minutes, hours and days.

Can this be done with the new C++11
namespace? If not, how should I go about this today?

I'm using g++-4.8.1 though presumably an answer should just target the C++11 spec.

std::tm tm = {};
std::stringstream ss("Jan 9 2014 12:35:34");
ss >> std::get_time(&tm, "%b %d %Y %H:%M:%S");
auto tp = std::chrono::system_clock::from_time_t(std::mktime(&tm));

Because GCC doesn't implement std::get_time you should also be able to write:

std::tm tm = {};
strptime("Thu Jan 9 12:35:34 2014", "%a, %d %b %Y %H:%M:%S", &tm);
auto tp = std::chrono::system_clock::from_time_t(std::mktime(&tm));