Home >Backend Development >C++ >How Can I Parse Historical Date Strings and Calculate Elapsed Time Using C 11\'s `std::chrono`?
Parsing Historical Date Strings into C 11 Date Representations
This question explores the possibilities of parsing historical date strings using C 11's std::chrono namespace. The goal is to calculate the time elapsed since a given date, with specific requirements for accessing data in terms of seconds, minutes, hours, and days.
std::chrono Approach
As queried, std::chrono provides a potential solution for this task. Here's a breakdown using the provided date string format:
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));
This code initializes a std::tm struct (tm), parses the date string using std::get_time (available from GCC 5 and later), and converts the parsed data into a std::chrono::time_point (tp).
Alternative for Pre-GCC 5
Prior to GCC 5, std::get_time is unavailable. In this case, an alternative exists:
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));
strptime() accomplishes the parsing, and the process then follows the same steps as with std::get_time.
Extracting Time Duration Components
Once the tp is obtained, the code can calculate the time difference and extract the various components:
auto elapsed = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now() - tp ); uint64_t days = elapsed.count() / 60 / 60 / 24; uint64_t hours = (elapsed.count() / 60 / 60) % 24; uint64_t minutes = (elapsed.count() / 60) % 60; uint64_t seconds = elapsed.count() % 60;
These values represent the time interval since the given date in terms of days, hours, minutes, and seconds.
The above is the detailed content of How Can I Parse Historical Date Strings and Calculate Elapsed Time Using C 11\'s `std::chrono`?. For more information, please follow other related articles on the PHP Chinese website!