Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 std::chrono 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.

like image 555
Drew Noakes Avatar asked Jan 09 '14 13:01

Drew Noakes


1 Answers

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)); 

GCC prior to version 5 doesn't implement std::get_time. You should also be able to write:

std::tm tm = {}; strptime("Thu Jan 9 2014 12:35:34", "%a %b %d %Y %H:%M:%S", &tm); auto tp = std::chrono::system_clock::from_time_t(std::mktime(&tm)); 
like image 145
Simple Avatar answered Sep 20 '22 17:09

Simple