Parsing Date Strings with C 11's std::chrono
When dealing with historical date strings, it's often necessary to parse them into C date representations for various computations. C 11's std::chrono namespace provides powerful tools for time handling.
Parsing a Date String
To parse a date string of the format "Thu Jan 9 12:35:34 2014," we can leverage the std::stringstream and std::get_time functions:
std::stringstream ss("Jan 9 2014 12:35:34"); std::tm tm = {}; ss >> std::get_time(&tm, "%b %d %Y %H:%M:%S");
This parses the string into a std::tm struct, which contains the individual time components.
Converting to a std::chrono::time_point
To obtain a std::chrono::time_point representing the parsed date, we use std::chrono::system_clock::from_time_t:
auto tp = std::chrono::system_clock::from_time_t(std::mktime(&tm));
Calculating Elapsed Time
With the std::chrono::time_point, we can easily calculate elapsed time from the specified historic date:
auto now = std::chrono::system_clock::now(); auto duration = now - tp;
Accessing Time Components
std::chrono::duration provides access to individual time components:
C 11 Support
GCC prior to version 5 does not implement std::get_time. However, an alternative using strptime is also available:
std::tm tm = {}; strptime("Thu Jan 9 2014 12:35:34", "%a %b %d %Y %H:%M:%S", &tm);
The above is the detailed content of How Can I Parse Date Strings and Perform Time Calculations Using C 11\'s std::chrono?. For more information, please follow other related articles on the PHP Chinese website!