Home >Backend Development >C++ >How to Parse Date Strings into C 11 Temporal Values?

How to Parse Date Strings into C 11 Temporal Values?

Linda Hamilton
Linda HamiltonOriginal
2024-11-29 17:12:15209browse

How to Parse Date Strings into C  11 Temporal Values?

Parsing Date Strings into C 11 Temporal Values

Date String Parsing

Given a historical date string in the format "Thu Jan 9 12:35:34 2014", the goal is to parse it into a suitable C representation.

C 11 std::chrono Approach

For the C 11 std::chrono namespace, a combination of the std::strptime function and std::chrono::system_clock can be utilized.

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

Note that std::get_time is not implemented in GCC prior to version 5.

Alternative Option

An alternative approach is to use the strptime function:

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

Duration Calculation

Once the date string is parsed into a temporal value, the difference between the current time and the parsed time can be calculated using std::chrono::duration. This duration provides access to the number of seconds, minutes, hours, and days elapsed.

The above is the detailed content of How to Parse Date Strings into C 11 Temporal Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn