Home > Backend Development > C++ > How Can I Parse Date Strings and Perform Time Calculations Using C 11\'s std::chrono?

How Can I Parse Date Strings and Perform Time Calculations Using C 11\'s std::chrono?

Patricia Arquette
Release: 2024-11-25 12:52:12
Original
849 people have browsed it

How Can I Parse Date Strings and Perform Time Calculations Using C  11's std::chrono?

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");
Copy after login

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));
Copy after login

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;
Copy after login

Accessing Time Components

std::chrono::duration provides access to individual time components:

  • duration.count() returns the total count of time units (seconds by default)
  • duration.seconds() retrieves seconds
  • duration.minutes() obtains minutes
  • duration.hours() fetches hours
  • duration.days() provides days

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template